MyBatis从入门到废弃一:从SqlSession实现增删改查

前言

   
 开博客这是率先次写体系作品,从心田上讲是有点担心自己写糟糕,写不全,毕竟是当做java/mybatis学习的进程想把读书的路径和遭逢的问题都总括下来,也让知识点在脑际里能形成一个连串。

    

支出条件

    idea2016、mybatis3、SQLServer2012

 

pom.xml、mybatis.xml、log4j.properties

 
 先贴上pom.xml是因为她间接和搭建开发条件和测试环境有涉及,mybatis.xml则是接连数据库,log4j.properties在读书阶段配置上促进我们观望SQL的执行意况。

1、pom.xml

图片 1图片 2

 <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>

View Code

2、mybatis.xml

图片 3图片 4

 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>

View Code

3、log4j.properties

图片 5图片 6

 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

View Code

 

配置mapper.xml

 
 mapper.xml在mybatis.xml是兼职处理sql的一个环节,各样映射和贯彻都在此地处理

<?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

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

@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

 @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

 @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

  @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

 @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();
        }
    }

  

总结

      添加、修改、删除的操作要调用sqlsession.commit(),不然数据无法入库的,我刚最先就淡忘了这多少个。

 

网站地图xml地图