当前位置: 首页 > 编程日记 > 正文

IDEA构建一个mybatis项目

目录结构如下:

在pom.xml中配置需要的jar包

  <dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.29</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.12</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.12</version></dependency>
</dependencies>

接下来新建config.properties配置文件将JDBC连接所需参数配置进去

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=123456

建一个model,Person.java

public class Person {private int id;private String userName ;private int age ;private String mobilePhone ;public  Person(){}public Person(int id,String userName, int age, String mobilePhone) {this.id = id;this.userName = userName;this.age = age;this.mobilePhone = mobilePhone;}public String getUserName() {return userName;}public int getId() {return id;}public void setId(int id) {this.id = id;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getMobilePhone() {return mobilePhone;}public void setMobilePhone(String mobilePhone) {this.mobilePhone = mobilePhone;}@Overridepublic String toString() {return "Person{" +"userName='" + userName + '\'' +", age=" + age +", mobilePhone='" + mobilePhone + '\'' +'}';}
}


配置mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><properties resource="config.properties"/><typeAliases><typeAlias type="model.Person" alias="Person"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><mappers><mapper resource="mapper/Person.xml"/></mappers>
</configuration>

配置日志打印log4j.properties

log4j.rootLogger=debug, stdout, Rlog4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p - %m%nlog4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=firestorm.loglog4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%nlog4j.logger.com.codefutures=DEBUG

配置mapper包下的Person.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com"><insert id="insertPerson" parameterType="Person" >INSERT INTO PERSON(ID,USERNAME,AGE,MOBILEPHONE)VALUES (#{id},#{userName},#{age},#{mobilePhone})</insert><select id="queryById" parameterType="int" resultType="Person">SELECT * FROM PERSON WHERE ID=#{id}</select><update id="updatePerson">UPDATE PERSON SET USERNAME=#{userName},AGE=#{age},MOBILEPHONE=#{mobilePhone} WHERE ID=#{id}</update>
</mapper>

写一个工具类来获取SqlSessionFactory和SqlSession

public class MybatisUtil {private final  static SqlSessionFactory sqlSessionFactory;static {String resource="mybatis-config.xml";Reader reader =null;try {reader = Resources.getResourceAsReader(resource);} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);}/*** 获取SqlSessionFactory* @return SqlSessionFactory*/public static SqlSessionFactory getSqlSessionFactory(){return sqlSessionFactory;}/*** 获取SqlSession* @return SqlSession*/public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();}/*** 关闭SqlSession*/public  static void closeSession(SqlSession sqlSession){if (sqlSession!=null)sqlSession.close();}}

最后测试

public class UserTest {SqlSession sqlSession ;@Testpublic void insertPerson(){sqlSession = MybatisUtil.getSqlSession();int id = 10000;String userName = "test";int age = 18;String mobilePhone = "18000000000";Person person = new Person();person.setId(id);person.setAge(age);person.setUserName(userName);person.setMobilePhone(mobilePhone);try{sqlSession.insert("insertPerson",person);sqlSession.commit();}catch (Exception e){e.printStackTrace();}finally {MybatisUtil.closeSession(sqlSession);}}@Testpublic void queryById(){sqlSession = MybatisUtil.getSqlSession();int id = 1;try{Person person = sqlSession.selectOne("queryById",id);sqlSession.commit();System.out.println(person.getUserName());}catch (Exception e){e.printStackTrace();}finally {MybatisUtil.closeSession(sqlSession);}}
}

最后测试,成功插入到数据库中

转载于:https://www.cnblogs.com/guodao/p/9702449.html

相关文章:

小程序在canvas上层做图片滚动

实现该功能踩过的坑 1.swiper的swiper-item中image图片无法在canvas的上层显示&#xff0c;会被canvas 覆盖 2.swiper的swiper-item 里面放 cover-image 会样式错乱 3.scroll-view里面放 cover-image 会样式错乱 解决方案&#xff1a;使用CSS样式实现&#xff0c;超出部分隐…

React是如何在后台运行的

React is a very popular JavaScript library. With over 5.5 million weekly downloads, React is enjoying great popularity. But not a lot of React developers know how React works under the hood. React是一个非常流行JavaScript库。 每周的下载量超过550万&#xff0…

H5播放视频流

代码 <html> <head> <title>视频直播</title> <meta charset"utf-8"> <link href"http://vjs.zencdn.net/5.5.3/video-js.css" rel"stylesheet"> <!-- If youd like to support IE8 --> <!-…

获取Java系统相关信息

1 package com.test;2 3 import java.util.Properties;4 import java.util.Map.Entry;5 6 import org.junit.Test;7 8 public class SystemTest {9 10 /** 11 * 获取Java系统相关信息 12 * throws Exception 13 */ 14 Test 15 public void testSys…

如何使用FaunaDB + GraphQL

I have one or two projects I maintain on Netlify, in addition to hosting my blog there. It’s an easy platform to deploy to, and has features for content management (CMS) and lambda functions (by way of AWS).除了在其中托管我的博客外&#xff0c;我在Netlify上…

POJ 1414 Life Line(搜索)

题意&#xff1a; 给定一块正三角形棋盘&#xff0c;然后给定一些棋子和空位&#xff0c;棋子序号为a&#xff08;1<a<9)&#xff0c;group的定义是相邻序号一样的棋子。 然后到C&#xff08;1<N<9&#xff09;棋手在空位放上自己序号C的棋子&#xff0c; 放完后&a…

MySQL_数据库操作语句

ZC&#xff1a;数据库名/表名/字段名 都使用小写字母 1、 创建 数据库 和 表 的时候&#xff0c;都要指定 编码方式为 utf-8 ! ! ! 因为 执行命令“show variables like char%;”后可以看到 character_set_database 的值为 latin1&#xff0c;即 默认创建数据库是使用的 字符编…

H5打开预览PDF,PPT等文件

实现代码&#xff1a; pdfUrl 写你的文件路径 <iframe :src"//www.xdocin.com/xdoc?_functo&_formathtml&_cache1&_xdocpdfUrl"width"100%"height"100%"frameborder"0"> </iframe> 可以直接打开看

广播代码_代码广播:专为编码而设计的24/7音乐

广播代码阅读本文时&#xff0c;您可以继续阅读Code Radio。 (You can go ahead and start listening to Code Radio while you read this) Most developers I know listen to music while they code. When the meetings are over, the headphones come out.我认识的大多数开发…

从 Android 静音看正确的查bug的姿势?

0、写在前面 没抢到小马哥的红包&#xff0c;无心回家了&#xff0c;回公司写篇文章安慰下自己TT。。话说年关难过&#xff0c;bug多多&#xff0c;时间久了难免头昏脑热&#xff0c;不辨朝暮&#xff0c;难识乾坤。。。艾玛&#xff0c;扯远了&#xff0c;话说谁没踩过坑&…

SecureCRT中sqlplus,使用Backspace删除时 ^H^H

在“Session Options” - "Terminal" - "Mapped Keys" - "Other mappings"&#xff0c;选择“Backspace sends delete”。转载于:https://www.cnblogs.com/Clark-cloud-database/p/7813867.html

在vue中使用vuex,修改state的值示例

1、 安装 vuex npm install vuex -S 2、在目录下创建store文件 3、 在store.js编辑一个修改state的方法 然后在mian.js中全局引入 最后在组件中使用 这个的功能是运用mutations 修改state中的值

软件开发 自由职业_自由职业? 这里有7个可以出售软件开发服务的地方

软件开发 自由职业Web developers need clients. This is true whether you are a full-time freelancer or you freelance on the side.Web开发人员需要客户。 无论您是全职自由职业者&#xff0c;还是身旁的自由职业者&#xff0c;都是如此。 So if youve ever asked: "…

生成SSH key

1、打开终端&#xff0c;输入下面的代码 &#xff0c;注意&#xff1a;$your_email为占位符&#xff0c;此处输入你自己的email ssh-keygen -t rsa -C "$your_email" 2、查看生成的公钥&#xff0c;输入下面的代码 cat ~/.ssh/id_rsa.pub 3、复制公钥&#xff08;公钥…

[转载]二叉树(BST,AVT,RBT)

二叉查找树(Binary Search Tree)是满足如下性质的二叉树&#xff1a;①若它的左子树非空&#xff0c;则左子树上所有结点的值均小于根结点的值&#xff1b;②若它的右子树非空&#xff0c;则右子树上所有结点的值均大于根结点的值&#xff1b;③左、右子树本身又各是一棵二叉查…

Invalid Host header 问题解决

出现该问的原因&#xff1a; 因为新版的 webpack-dev-server 出于安全考虑&#xff0c;默认检查 hostname&#xff0c;如果hostname不是配置内的就不能访问。 解决办法&#xff1a;设置跳过host检查 打开你的项目全局搜索 devServer &#xff0c;在 devServer 里面添加 &quo…

react hooks使用_为什么要使用React Hooks?

react hooks使用The first thing you should do whenever youre about to learn something new is ask yourself two questions -每当您要学习新东西时&#xff0c;应该做的第一件事就是问自己两个问题- Why does this thing exist? 为什么这东西存在&#xff1f; What probl…

算法 - 字符串匹配

http://blog.csdn.net/linhuanmars/article/details/20276833 转载于:https://www.cnblogs.com/qlky/p/7817471.html

工作流入门链接

百度百科-工作流 http://baike.baidu.com/link?urlZjElBNByyZz_ItLtd_Uqt3Sadcwv0-4CDO806vKQWJDuUOFybbkzpg8GOB1EU71w8bT4x64RoRXBrFXa7o_dK 企业应用工作流的好处http://jingyan.baidu.com/article/90895e0fe9c56164ec6b0b24.html工作流管理的好处http://blog.sina.com.cn/…

uniapph5配置index.html模板路径不生效解决办法

很简单&#xff0c;关闭应用再重新启动试试&#xff0c;还不行的话&#xff0c;重启IDE

终端软件升级功能开发_5个很棒的终端技巧可帮助您升级为开发人员

终端软件升级功能开发There are plenty of beginner tutorials around that help you learn command line basics, such as cd, ls, pwd and so on...but what about that fancy magic youve seen more experienced developers use?周围有很多初学者教程可以帮助您学习命令行基…

自定义左右侧滑菜单

实现效果&#xff1a; 左右侧滑菜单&#xff0c;侧滑栏占主屏比为60%监听触控&#xff0c;自定义滑动动画&#xff0c;当侧边栏滑动超过50%松开触控将自动滑动到60%&#xff0c;未超过50%松开触控回归侧边栏隐藏为主屏设置蒙版效果&#xff0c;根据侧滑菜单的占屏比设置主屏蒙版…

uniapp设置模板路径页面样式混乱解决办法

乱了就在html里面加上下面这行代码试试 <link rel"stylesheet" href"<% BASE_URL %>static/index.css" /> <meta name"viewport" content"widthdevice-width, initial-scale1.0, user-scalableno, minimum-scale1.0, maxim…

JavaScript获取当前日期,昨天,今天日期以及任意天数间隔日期

<script language"JavaScript" type"text/javascript"> function GetDateStr(AddDayCount) { var dd new Date(); dd.setDate(dd.getDate()AddDayCount);//获取AddDayCount天后的日期 var y dd.getYear(); var m dd.getMonth()1;//获取当前月份…

snapd_snapd使管理Nextcloud变得轻而易举

snapdAs I’ve described in both my Linux in Action book and Linux in Motion course, Nextcloud is a powerful way to build a file sharing and collaboration service using only open source software running on your own secure infrastructure. It’s DropBox, Skyp…

atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty  HttpListener...

atitit.跨架构 bs cs解决方案. 自定义web服务器的实现方案 java .net jetty HttpListener 1. 自定义web服务器的实现方案&#xff0c;基于原始socket vs 基于tcpListener vs 基于HttpListener1 2. download1 3. Lib3 4. Code3 5. HttpListener类4 6. Reef5 1. 自定义web服务器…

Python高级函数--map/reduce

名字开头大写 后面小写&#xff1b;练习&#xff1a; 1 def normalize(name): 2 return name[0].upper() name[1:].lower() 3 L1 [adam, LISA, barT] 4 L2 list(map(normalize, L1)) 5 print(L2) reduce求积&#xff1a; 1 from functools import reduce 2 3 def prod(…

样式集(9) - 切换Tab菜单

先上效果图 下面是以vue实现的示例代码&#xff1a; 代码解析&#xff1a; 很简单的代码&#xff0c;直接复制粘贴使用吧~ 别忘记一键三连哦&#xff0c;点赞&#xff0c;收藏&#xff0c;关注&#xff0c;谢谢~ 后续持续更新更多干货哦&#xff01;&#xff01; <temp…

python字典{:4}_Python字典101:详细的视觉介绍

python字典{&#xff1a;>4}欢迎 (Welcome) In this article, you will learn how to work with Python dictionaries, an incredibly helpful built-in data type that you will definitely use in your projects.在本文中&#xff0c;您将学习如何使用Python字典&#xff…

asp.net提交危险字符处理方法之一

在form表单提交前&#xff0c;可以在web页面&#xff0c;submit按钮的click事件中&#xff0c;使用js函数对&#xff0c;可能有危险字符的内容进行编码。 有3个函数可用&#xff1a; encodeURI() 函数可把字符串作为 URI 进行编码。 escape() 函数可对字符串进行编码&#xff0…