MyBatis
MyBatis从入门到放弃一:从SqlSession实现增删改查
前言
开博客这是第一次写系列文章,从内心上讲是有点担心自己写不好,写不全,毕竟是作为java/mybatis学习的过程想把学习的路线和遇到的问题都总结下来,也让知识点在脑海里能形成一个体系。
开发环境
idea2016、mybatis3、SQLServer2012
pom.xml、mybatis.xml、log4j.properties
先贴上pom.xml是因为他直接和搭建开发环境和测试环境有关系,mybatis.xml则是连接数据库,log4j.properties在学习阶段配置上有助于我们观察SQL的执行情况。
1、pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
2、mybatis.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE configuration
3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6
7 <!-- MyBatis针对SqlServer进行的配置 -->
8 <typeAliases>
9 <typeAlias alias="User" type="com.autohome.model.User"/>
10 <typeAlias alias="Teacher" type="com.autohome.model.Teacher" />
11 <typeAlias alias="Student" type="com.autohome.model.Student" />
12 </typeAliases>
13 <environments default="development">
14 <environment id="development">
15 <transactionManager type="JDBC"/>
16 <dataSource type="POOLED">
17 <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
18 <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=test"/>
19 <property name="username" value="sa"/>
20 <property name="password" value="0"/>
21 </dataSource>
22 </environment>
23 </environments>
24
25
26 <mappers>
27 <mapper resource="mapper/User.xml"/>
28 <mapper resource="mapper/Student.xml"/>
29 </mappers>
30 </configuration>
3、log4j.properties
1 ### Log4j配置 ###
2 ### 与Spring结合需要在web.xml中指定此文件位置,并添加监听器 ###
3 #定义log4j的输出级别和输出目的地(目的地可以自定义名称,和后面的对应)
4 #[ level ] , appenderName1 , appenderName2
5 log4j.rootLogger=DEBUG,console,file
6
7 #-----------------------------------#
8 #1 定义日志输出目的地为控制台
9 log4j.appender.console = org.apache.log4j.ConsoleAppender
10 log4j.appender.console.Target = System.out
11 log4j.appender.console.Threshold=DEBUG
12 ####可以灵活地指定日志输出格式,下面一行是指定具体的格式 ###
13 #%c: 输出日志信息所属的类目,通常就是所在类的全名
14 #%m: 输出代码中指定的消息,产生的日志具体信息
15 #%n: 输出一个回车换行符,Windows平台为"/r/n",Unix平台为"/n"输出日志信息换行
16 log4j.appender.console.layout = org.apache.log4j.PatternLayout
17 log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
18
19 #-----------------------------------#
20 #2 文件大小到达指定尺寸的时候产生一个新的文件
21 log4j.appender.file = org.apache.log4j.RollingFileAppender
22 #日志文件输出目录
23 log4j.appender.file.File=log/tibet.log
24 #定义文件最大大小
25 log4j.appender.file.MaxFileSize=10mb
26 ###输出日志信息###
27 #最低级别
28 log4j.appender.file.Threshold=ERROR
29 log4j.appender.file.layout=org.apache.log4j.PatternLayout
30 log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
31
32 #-----------------------------------#
33 #3 druid
34 log4j.logger.druid.sql=INFO
35 log4j.logger.druid.sql.DataSource=info
36 log4j.logger.druid.sql.Connection=info
37 log4j.logger.druid.sql.Statement=info
38 log4j.logger.druid.sql.ResultSet=info
39
40 #4 mybatis 显示SQL语句部分
41 log4j.logger.org.mybatis=DEBUG
42 #log4j.logger.cn.tibet.cas.dao=DEBUG
43 #log4j.logger.org.mybatis.common.jdbc.SimpleDataSource=DEBUG#
44 #log4j.logger.org.mybatis.common.jdbc.ScriptRunner=DEBUG#
45 #log4j.logger.org.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG#
46 #log4j.logger.java.sql.Connection=DEBUG
47 log4j.logger.java.sql=DEBUG
48 log4j.logger.java.sql.Statement=DEBUG
49 log4j.logger.java.sql.ResultSet=DEBUG
50 log4j.logger.java.sql.PreparedStatement=DEBUG
配置mapper.xml
mapper.xml在mybatis.xml是专职处理sql的一个环节,各种映射和实现都在这里处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?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.autohome.mapper.User" > <!-- 查询全部用户 --> <select id= "queryUsers" resultType= "com.autohome.model.User" > select * from t_userinfo </select> <!-- 按照ID查询 --> <select id= "queryUserById" parameterType= "int" resultType= "com.autohome.model.User" > select * from t_userinfo where id=#{id} </select> <select id= "queryUserByAddress" resultType= "com.autohome.model.User" > select * from t_userinfo where name=#{name,javaType=String,jdbcType=VARCHAR} and address=#{address} </select> <!-- 添加用户 --> <insert id= "insertUsers" parameterType= "com.autohome.model.User" > insert into t_userinfo (name,address) values(#{name},#{address}) </insert> <!-- 修改用户 --> <update id= "updateUsers" parameterType= "com.autohome.model.User" > update t_userinfo set name=#{name},address=#{address} where id=#{id} </update> <!-- 删除用户 --> <delete id= "deleteUsers" parameterType= "int" > delete t_userinfo where id=#{id} </delete> </mapper> |
建立单元测试
1、准备工作,我建立的是控制台程序,所以在使用sqlsession前先创建sqlsessionfactory。当然,还要加载log4j.properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
SqlSessionFactory sqlSessionFactory= null ; @Before public void BeforeClass(){ try { InputStream is=Resources.getResourceAsStream( "log4j.properties" ); PropertyConfigurator.configure(is); Reader reader = Resources.getResourceAsReader( "mybatis.xml" ); sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } |
2、queryUsers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@Test public void queryUsers() throws Exception { //线程不安全类型,放在方法体内 SqlSession sqlSession= null ; try { sqlSession=sqlSessionFactory.openSession(); List<User> list = sqlSession.selectList( "com.autohome.mapper.User.queryUsers" ); System.out.println( "size:" +list.size()); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } } |
3、queryUserById
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@Test public void queryUserById() { SqlSession sqlSession= null ; try { sqlSession=sqlSessionFactory.openSession(); User user = sqlSession.selectOne( "com.autohome.mapper.User.queryUserById" , 2 ); System.out.println( "id:" +user.getId()+ ",name:" +user.getName()+ "," +user.getAddress()); } catch (Exception e){ e.printStackTrace(); } finally { sqlSession.close(); } } |
4、insertUser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
@Test public void insertUser(){ SqlSession sqlSession= null ; try { sqlSession=sqlSessionFactory.openSession(); User user = new User(); user.setName( "kobe" ); user.setAddress( "usa" ); int result = sqlSession.insert( "com.autohome.mapper.User.insertUsers" ,user); sqlSession.commit(); if (result> 0 ){ System.out.println( "insert success...." ); } else { System.out.println( "insert error...." ); } } catch (Exception e){ e.printStackTrace(); } finally { sqlSession.close(); } } |
5、updateUser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
@Test public void updateUser(){ SqlSession sqlSession= null ; try { sqlSession=sqlSessionFactory.openSession(); User user = new User(); user.setId( 36 ); user.setName( "kobe" ); user.setAddress( "usa" ); int result = sqlSession.update( "com.autohome.mapper.User.updateUsers" ,user); sqlSession.commit(); if (result> 0 ){ System.out.println( "update success...." ); } else { System.out.println( "update error...." ); } } catch (Exception e){ e.printStackTrace(); } finally { sqlSession.close(); } } |
6、deleteUser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@Test public void deleteUser(){ SqlSession sqlSession= null ; try { sqlSession=sqlSessionFactory.openSession(); int result = sqlSession.delete( "com.autohome.mapper.User.deleteUsers" , 49 ); sqlSession.commit(); if (result> 0 ){ System.out.println( "delete success...." ); } else { System.out.println( "delete error...." ); } } catch (Exception e){ e.printStackTrace(); } finally { sqlSession.close(); } } |