• myBatis实例


    一.搭建环境,

    建立数据库

    1 CREATE TABLE user(
    2        id int(11) not NULL AUTO_INCREMENT,
    3        userName varchar(50) DEFAULT NULL,
    4        userAge int(11) DEFAULT NULL,
    5        userAddress varchar(200) DEFAULT NULL,
    6        PRIMARY KEY(id)
    7 )ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

    建立一个myBatis的java项目(不需要web项目)

    然后倒入jar包

    建总配置文件:

    在src下建configration包.在建Configurations.xml文件

    代码如下:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE configuration PUBLIC " -//mybatis.org//DTD Config 3.0//EN"
     3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
     4 <configuration>
     5     <typeAliases>
     6         <typeAlias type="com.user.User" alias="User"/>
     7     </typeAliases>
     8     <environments default="development">
     9         <environment id="development">
    10             <transactionManager type="JDBC" />
    11             <dataSource type="POOLED">
    12                 <property name="driver" value="com.mysql.jdbc.Driver"/>
    13                 <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
    14                 <property name="username" value="root"/>
    15                 <property name="password" value="123"/>
    16             </dataSource>
    17         </environment>
    18     </environments>
    19     
    20     <mappers>
    21         <mapper resource="configration/User.xml"/>

        </mappers> 24 </configuration>

    建user的实体类和映射文件:

    com.user.User代码:

     1 package com.user;
     2 
     3 public class User {
     4     private int id;
     5     private String userName;
     6     private String userAge;
     7     private String userAddress;
     8     public int getId() {
     9         return id;
    10     }
    11     public void setId(int id) {
    12         this.id = id;
    13     }
    14     public String getUserName() {
    15         return userName;
    16     }
    17     public void setUserName(String userName) {
    18         this.userName = userName;
    19     }
    20     public String getUserAge() {
    21         return userAge;
    22     }
    23     public void setUserAge(String userAge) {
    24         this.userAge = userAge;
    25     }
    26     public String getUserAddress() {
    27         return userAddress;
    28     }
    29     public void setUserAddress(String userAddress) {
    30         this.userAddress = userAddress;
    31     }
    32     
    33 }

    configration包下见User.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="User">
        <select id="selectUserById" parameterType="int" resultType="User">
            select * from user where id=#{id}
        </select>
        <select id="selectUserList" parameterType="int" resultType="User">
            select * from user 
        </select>
     <insert id="insertUser" keyProperty="id" useGeneratedKeys="true"  parameterType="user">
        insert into user
            (userName,userAge)
            values
            (#{userName},#{userName})
        </insert>
    </mapper>

    建测试类

     1 package test;
     2 
     3 import java.io.Reader;
     4 import java.util.List;
     5 
     6 import org.apache.ibatis.io.Resources;
     7 import org.apache.ibatis.session.SqlSession;
     8 import org.apache.ibatis.session.SqlSessionFactory;
     9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    10 
    11 import com.user.User;
    12 
    13 public class Test {
    14     private static SqlSessionFactory sqlSessionFactory;
    15     private static Reader reader;
    16 
    17     static {
    18         try {
    19             reader = Resources.getResourceAsReader("configration/Configurations.xml");
    20             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    21         } catch (Exception e) {
    22             e.printStackTrace();
    23         }
    24     }
    25     public static void main(String[] args) {
    26         SqlSession session = sqlSessionFactory.openSession();
    27         try {
    28             //User user = (User) session.selectOne("User.selectUserById", 2);
    29             List<User> list=session.selectList("User.selectUserList");
    30             for(User user:list){
    31                 System.out.println("姓名:"+user.getUserName());
    32                 System.out.println("年龄"+user.getUserAge());
    33                 System.out.println("地址:"+user.getUserAddress());
    34                 System.out.println("-----------------------------------------------------------");
    35             }
    36             
    37         } catch (Exception e) {
    38             System.out.println("出现异常了.....");
    39             e.printStackTrace();
    40         } finally {
    41             session.close();
    42         }
    43     }
    44 }

    当你查看到从数据库中读取的数据时,说明环境搭建完毕了

    如何获取插入数据的主键值呢?

    package test;
    
    import java.io.Reader;
    import java.util.List;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import com.user.User;
    
    public class Run {
        private static SqlSessionFactory sqlSessionFactory;
        private static Reader reader;
    
        static {
            try {
                reader = Resources.getResourceAsReader("mybatis.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            SqlSession session = sqlSessionFactory.openSession();
            try {
                User u=new User();
                u.setUserAge(255);
                u.setUserName("思思博士");
                int count=session.insert("User.insertUser",u);//count受影响的行数
                session.commit();
                System.out.println("插入数据的id值:>>>>>>>>"+u.getId());
            } catch (Exception e) {
                System.out.println("出现异常了.....");
                e.printStackTrace();
            } finally {
                session.close();
            }
        }
    }

    上面的count是受影响的行数

    u.getId()才是插入数据的主键的id值

    二.用接口的方式实现编程.

    建立IUserOperation.java

     1 package inter;
     2 
     3 import java.util.List;
     4 
     5 import com.user.User;
     6 
     7 public interface IUserOperation {
     8     public User selectUserById(int id);
     9     public List<User> selectUserList();
    10 }

    建立IUser.xml.

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     4 
     5 <mapper namespace="inter.IUserOperation">
     6     <select id="selectUserById" parameterType="int" resultType="User">
     7         select * from user where id=#{id}
     8     </select>
     9     <select id="selectUserList" resultType="User">
    10         select * from user 
    11     </select>
    12 </mapper>

    注意这个地方的namspace就不可以随意取名字了.必须是实现接口的地址.

    在总配置文件中mappers添加一条xml:<mapper resource="configration/IUser.xml"/>

    添加测试类:

     1 package test;
     2 
     3 import inter.IUserOperation;
     4 
     5 import java.io.Reader;
     6 import java.util.List;
     7 
     8 import org.apache.ibatis.io.Resources;
     9 import org.apache.ibatis.session.SqlSession;
    10 import org.apache.ibatis.session.SqlSessionFactory;
    11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    12 
    13 import com.user.User;
    14 
    15 /**
    16  * 以接口的方式编程
    17  * 如果以这种方式的话,那么对应的sql的xml配置文件中的namespace必须是实现接口的具体地址
    18  */
    19 public class TestInterface {
    20     private static SqlSessionFactory sqlSessionFactory;
    21     private static Reader reader;
    22 
    23     static {
    24         try {
    25             reader = Resources.getResourceAsReader("configration/Configurations.xml");
    26             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    27         } catch (Exception e) {
    28             e.printStackTrace();
    29         }
    30     }
    31     public static void main(String[] args) {
    32         SqlSession session = sqlSessionFactory.openSession();
    33         try {
    34             IUserOperation userOperation=session.getMapper(IUserOperation.class);
    35             /*User user=userOperation.selectUserById(3);
    36             System.out.println(user.getUserAddress());
    37             System.out.println(user.getUserName());*/
    38             
    39             List<User> list=userOperation.selectUserList();
    40             for(User user:list){
    41                 System.out.println("姓名:"+user.getUserName());
    42                 System.out.println("年龄:"+user.getUserAge());
    43                 System.out.println("地址:"+user.getUserAddress());
    44                 System.out.println("--------------------------------");
    45             }
    46             
    47             
    48         } catch (Exception e) {
    49             System.out.println("出现异常了.....");
    50             e.printStackTrace();
    51         } finally {
    52             session.close();
    53         }
    54     }
    55 }

     三,使用myBatis完成增删改查.

    重新修改以下文件.

    IUser.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     4 
     5 <mapper namespace="inter.IUserOperation">
     6 <!-- 返回list数据集时使用的返回map -->
     7     <resultMap type="User" id="resultListUserMap">
     8         <id column="id" property="id" />
     9         <result column="userName" property="userName"/>
    10         <result column="userAge" property="userAge"/>
    11         <result column="userAddress" property="userAddress"/>
    12     </resultMap>
    13     <select id="selectUserById" parameterType="int" resultType="User">
    14         select * from user where id=#{id}
    15     </select>
    16     <select id="selectUsers" parameterType="String" resultMap="resultListUserMap">
    17         select * from user where userName like #{userName}
    18     </select>
    19     <!-- 
    20         执行增加操作的SQL语句.id和parameterType分别与IUserOperation接口中的
    21         adUser方法的名字和参数类型一致.以#{name}的形式引用User参数的name属性.
    22         myBatis将使用反射读取User参数的此属性.#{name}中name大小写敏感.
    23         seGeneratedKeys设置为true,表明要myBatis获取自由数据库自动生成的主键;
    24         keyProperty="id"指定把获取到的主键值注入到User的id属性    
    25      -->    
    26     <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
    27         insert into user(userName,userAge,userAddress)
    28         values(#{userName},#{userAge},#{userAddress});
    29     </insert>
    30     
    31     <update id="updateUser" parameterType="User">
    32         update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} 
    33         where id=#{id}
    34     </update>
    35     
    36     <delete id="deleteUser" parameterType="int">
    37         delete from user where id=#{id}
    38     </delete>
    39     
    40 </mapper>

    IUserOperation.java

     1 package inter;
     2 
     3 import java.util.List;
     4 
     5 import com.user.User;
     6 
     7 public interface IUserOperation {
     8     public User selectUserById(int id);    
     9     public List<User> selectUsers(String userName);
    10     public void addUser(User user);
    11     public void updateUser(User user);
    12     public void deleteUser(int id);
    13 }

    Test1.java

      1 package test;
      2 
      3 import inter.IUserOperation;
      4 
      5 import java.io.Reader;
      6 import java.util.List;
      7 
      8 import org.apache.ibatis.io.Resources;
      9 import org.apache.ibatis.session.SqlSession;
     10 import org.apache.ibatis.session.SqlSessionFactory;
     11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     12 
     13 import com.user.User;
     14 
     15 public class Test1 {
     16     private static SqlSessionFactory sqlSessionFactory;
     17     private static Reader reader;
     18     static {
     19         try {
     20             reader = Resources
     21                     .getResourceAsReader("configration/Configurations.xml");
     22             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
     23         } catch (Exception e) {
     24             e.printStackTrace();
     25         }
     26     }
     27     public void getUserList(String userName){
     28         SqlSession session=sqlSessionFactory.openSession();
     29         try {
     30             IUserOperation userOperation=session.getMapper(IUserOperation.class);
     31         List<User> users=userOperation.selectUsers(userName);
     32         for(User user:users){
     33             System.out.println("id:"+user.getId());
     34             System.out.println("name:"+user.getUserName());
     35             System.out.println("age:"+user.getUserAge());
     36             System.out.println("address:"+user.getUserAddress());
     37             System.out.println("-----------------");
     38         }
     39         } catch (Exception e) {
     40             System.out.println("查询出错了......");
     41         }finally{
     42             session.close();
     43         }
     44         
     45     }
     46     
     47     /**
     48      * 添加数据,必须提交事务,否则不会写入dao数据库
     49      * @param args
     50      */
     51     public void addUser(){
     52         User user=new User();
     53         user.setUserAddress("安徽,舒城");
     54         user.setUserAge(26);
     55         user.setUserName("思思博士");
     56         SqlSession session=sqlSessionFactory.openSession();
     57         try {
     58             IUserOperation userOperation=session.getMapper(IUserOperation.class);
     59             userOperation.addUser(user);
     60             session.commit();
     61             System.out.println("当前增加的id为:"+user.getId());
     62         } catch (Exception e) {
     63             System.out.println("添加出现异常啦........");
     64         }finally{
     65             session.close();
     66         }        
     67     }
     68     
     69     /**
     70      * 
     71      * @param args
     72      */
     73     public void updateUser(){
     74         User user=new User();
     75         user.setUserAddress("安徽,舒城,千人桥镇");
     76         user.setUserAge(260);
     77         user.setUserName("思思博士");
     78         user.setId(4);
     79         SqlSession session=sqlSessionFactory.openSession();
     80         try {
     81             IUserOperation userOperation=session.getMapper(IUserOperation.class);
     82             userOperation.updateUser(user);
     83             session.commit();
     84             //System.out.println("当前增加的id为:"+user.getId());
     85         } catch (Exception e) {
     86             System.out.println("更新出现异常啦........");
     87         }finally{
     88             session.close();
     89         }        
     90     }
     91     
     92     /**
     93      * 删除数据
     94      * @param args
     95      */
     96     public void deleteUser(int id){
     97         SqlSession session=sqlSessionFactory.openSession();
     98         try {
     99             IUserOperation userOperation=session.getMapper(IUserOperation.class);
    100             userOperation.deleteUser(id);
    101             session.commit();
    102             System.out.println("数据删除成功");
    103         } catch (Exception e) {
    104             System.out.println("数据删除失败啦.....");
    105         }
    106         finally{
    107             session.close();
    108         }
    109     }
    110     
    111     
    112     public static void main(String[] args) {
    113         Test1 test1=new Test1();
    114         //查询列表
    115         test1.getUserList("%");        
    116         //test1.addUser();//添加数据
    117         //test1.updateUser();//更新数据
    118         //test1.deleteUser(3);//删除数据
    119     }
    120 }

     四.联合查询:

    IJoinUser.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     4 
     5 <mapper namespace="inter.IUserJoinOperation">
     6     <resultMap type="User" id="resultListUserMapss">
     7         <id column="id" property="id" />
     8         <result column="userName" property="userName"/>
     9         <result column="userAge" property="userAge"/>
    10         <result column="userAddress" property="userAddress"/>
    11     </resultMap>
    12     <!-- User联合文章进行查询方法之一的配置(多对一的方式) -->
    13     <resultMap type="News" id="resultUserNewsListMap">
    14         <id property="id" column="Id" />
    15         <result property="title" column="title" />
    16         <result property="content" column="content" />    
    17         <association property="user" javaType="User">
    18             <id property="id" column="id" />
    19             <result property="userName" column="userName"/>
    20             <result property="userAddress" column="userAddress"/>
    21         </association> 
    22     </resultMap>
    23     
    24     <select id="getUserNewsList" parameterType="int" resultMap="resultUserNewsListMap">
    25         select user.id,user.userName,user.userAge,user.userAddress,
    26         news.id,news.userId,news.title,news.content
    27         from user,news
    28         where user.id=news.userId and user.id=#{id}
    29     </select>
    30     
    31 </mapper>

    IUserOperation.java

    1 package inter;
    2 
    3 import java.util.List;
    4 
    5 import com.user.News;
    6 
    7 public interface IUserJoinOperation {
    8     public List<News> getUserNewsList(int userId);
    9 }

    测试类:

     1 package test;
     2 
     3 import inter.IUserJoinOperation;
     4 import inter.IUserOperation;
     5 
     6 import java.io.Reader;
     7 import java.util.List;
     8 
     9 import org.apache.ibatis.io.Resources;
    10 import org.apache.ibatis.session.SqlSession;
    11 import org.apache.ibatis.session.SqlSessionFactory;
    12 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    13 
    14 import com.user.News;
    15 import com.user.User;
    16 
    17 public class Test2 {
    18     private static SqlSessionFactory sqlSessionFactory;
    19     private static Reader reader;
    20     static {
    21         try {
    22             reader = Resources
    23                     .getResourceAsReader("configration/Configurations.xml");
    24             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    25         } catch (Exception e) {
    26             e.printStackTrace();
    27         }
    28     }
    29     /**
    30      * 联合查询
    31      * @param args
    32      */
    33     public void getUserNews(int userId){
    34         SqlSession session=sqlSessionFactory.openSession();
    35         try {
    36             IUserJoinOperation joinOperation=session.getMapper(IUserJoinOperation.class);
    37             List<News> newsList=joinOperation.getUserNewsList(userId);
    38             for(News news:newsList){
    39                 System.out.println("id:"+news.getId());
    40                 System.out.println("title:"+news.getTitle());
    41                 System.out.println("content:"+news.getContent());
    42                 System.out.println("userId:"+news.getUser().getId());
    43                 System.out.println("name:"+news.getUser().getUserName());
    44                 System.out.println("age:"+news.getUser().getUserAge());
    45                 System.out.println("address:"+news.getUser().getUserAddress());
    46                 System.out.println("------------------------------------");
    47             }
    48             System.out.println("输出完毕....");
    49         } catch (Exception e) {
    50             System.out.println("联合查询失败啦.......");
    51         }
    52         finally{
    53             session.close();
    54         }
    55     }
    56     
    57     public static void main(String[] args) {
    58         Test2 test2=new Test2();
    59         //查询列表
    60         test2.getUserNews(4);
    61     }
    62 }

    其实还可以用另外一种方法:

    修改IJoinUser.xml文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     4 
     5 <mapper namespace="inter.IUserJoinOperation">
     6     <resultMap type="User" id="resultListUserMapss">
     7         <id column="id" property="id" />
     8         <result column="userName" property="userName"/>
     9         <result column="userAge" property="userAge"/>
    10         <result column="userAddress" property="userAddress"/>
    11     </resultMap>
    12     <!-- User联合文章进行查询方法之一的配置(多对一的方式) -->
    13     <resultMap type="News" id="resultUserNewsListMap">
    14         <id property="id" column="Id" />
    15         <result property="title" column="title" />
    16         <result property="content" column="content" />
    17         <association property="user" resultMap="resultListUserMapss" javaType="User" />
    18         <!-- <association property="user" javaType="User">
    19             <id property="id" column="id" />
    20             <result property="userName" column="userName"/>
    21             <result property="userAddress" column="userAddress"/>
    22         </association> -->
    23     </resultMap>
    24     
    25     <select id="getUserNewsList" parameterType="int" resultMap="resultUserNewsListMap">
    26         select user.id,user.userName,user.userAge,user.userAddress,
    27         news.id,news.userId,news.title,news.content
    28         from user,news
    29         where user.id=news.userId and user.id=#{id}
    30     </select>
    31     
    32 </mapper>

    这个地方我测试了一下,不知道为什么总是只能查出一条语句,但是sql语句直接在mysql中查询的话,可以查询多条的,哪位大神知道答案的,请告知啊.

    本文非原创:

    http://blog.csdn.net/techbirds_bao/article/details/9233599/

  • 相关阅读:
    数据库设计三大范式
    MySQL笔试题搜罗
    [转载]MySql事物处理
    网页错误代码大全
    【转载】linux环境下大数据网站搬家
    Linux常用命令
    MongoDB概述
    Linux系统下通过命令行对mysql数据进行备份和还原
    wamp提示:与服务器的连接断开,请检查网络状况与服务器的运行状态的解决方法
    HDU 4578 线段树各种区间操作
  • 原文地址:https://www.cnblogs.com/guoyansi19900907/p/4462449.html
Copyright © 2020-2023  润新知