mybatis 基于配置文件的demo

项目工程如图:

创建数据库:

1 CREATE TABLE myuser(
2     id     INT PRIMARY KEY,
3     username VARCHAR(20),
4     age     INT,
5     PASSWORD VARCHAR(20)
6 );

mybatis加载文件:configuration.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   <!-- 指定properties配置文件,数据库相关 -->
 8   <properties resource="mysql.properties"></properties>
 9   
10   <!-- 指定Mybatis使用log4j -->
11   <settings>
12      <setting name="logImpl" value="LOG4J"/>
13   </settings>
14       
15   <environments default="development">
16     <environment id="development">
17       <transactionManager type="JDBC"/>
18       <dataSource type="POOLED">
19           
20         <property name="driver" value="com.mysql.jdbc.Driver"/>
21         <property name="url" value="jdbc:mysql://localhost:3306/my_DB"/>
22         <property name="username" value="root"/>
23         <property name="password" value="123456"/>
24          
25          <!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
26          <!-- <property name="driver" value="${driver}"/>
27          <property name="url" value="${url}"/>
28          <property name="username" value="${username}"/>
29          <property name="password" value="${password}"/> -->
30          
31       </dataSource>
32     </environment>
33   </environments>
34   
35   
36   <mappers>
37     <mapper resource="mapping.xml"/>
38   </mappers>
39   
40 </configuration>

映射文件:mapping.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>   
 2 <!DOCTYPE mapper   
 3 PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
 4 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> 
 5 <mapper namespace="dao.UserDao">
 6 
 7     <select id="updateById" parameterType="entity.MyUser">
 8         UPDATE myuser SET age=#{age} WHERE id=#{id}
 9     </select>
10 
11     <select id="deleteById" parameterType="int">
12         DELETE FROM myuser WHERE id=#{id}
13     </select>
14 
15     <select id="insert" parameterType="entity.MyUser">
16         INSERT INTO myuser VALUES(#{id},#{username},#{age},#{password})
17     </select>
18 
19     <resultMap type="entity.MyUser" id="ResultListUser">
20         <id column="id" property="id" />
21         <result column="age" property="age" />
22         <result column="username" property="username" />
23         <result column="password" property="password" />
24     </resultMap>
25 
26     <select id="findAllUser" parameterType="string" resultMap="ResultListUser">
27         SELECT * FROM myuser WHERE PASSWORD LIKE "%"#{PASSWORD}"%"
28     </select>
29 
30    <select id="getUserById" parameterType="int" resultType="entity.MyUser" > 
31       select * from myuser where id = #{id}
32    </select>
33 
34 </mapper>

创建接口:UserDao.java

 1 package dao;
 2 
 3 import java.util.List;
 4 
 5 import entity.MyUser;
 6 
 7 public interface UserDao {
 8 
 9     public void updateById(MyUser user);
10     
11     public void deleteById(int id);
12     
13     public void insert(MyUser user);
14     
15     public MyUser getUserById(int id);
16     
17     public List<MyUser> findAllUser(String str);
18     
19 }

创建与数据库表字段对应的类:MyUser.java

 1 package entity;
 2 
 3 public class MyUser {
 4 
 5     private int id;
 6     private int age;
 7     private String username;
 8     private String password;
 9     public int getId() {
10         return id;
11     }
12     public void setId(int id) {
13         this.id = id;
14     }
15     public int getAge() {
16         return age;
17     }
18     public void setAge(int age) {
19         this.age = age;
20     }
21     public String getUsername() {
22         return username;
23     }
24     public void setUsername(String username) {
25         this.username = username;
26     }
27     public String getPassword() {
28         return password;
29     }
30     public void setPassword(String password) {
31         this.password = password;
32     }
33     @Override
34     public String toString() {
35         return "MyUser [id=" + id + ", age=" + age + ", username=" + username + ", password=" + password + "]";
36     }
37     
38     
39     
40 }
View Code

进行测试:UserDaoTest.java

  1 package dao;
  2 
  3 import java.io.IOException;
  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 import org.junit.Test;
 11 
 12 import entity.MyUser;
 13 
 14 public class UserDaoTest {
 15 
 16     @Test
 17     public void testUpdateByid() {
 18         
 19         SqlSession sqlSession = getSessionFactory().openSession();  
 20         try {
 21             UserDao userDao = sqlSession.getMapper(UserDao.class);  
 22             MyUser user = userDao.getUserById(3);
 23             user.setAge(12);
 24             userDao.updateById(user);
 25             sqlSession.commit();
 26         
 27         }
 28         finally {
 29             sqlSession.close();
 30         }
 31         
 32     }
 33     
 34     @Test
 35     public void testDeleteById() {
 36         
 37         SqlSession sqlSession = getSessionFactory().openSession();  
 38         try {
 39             UserDao userDao = sqlSession.getMapper(UserDao.class);  
 40             userDao.deleteById(8);
 41             sqlSession.commit();
 42         
 43         }
 44         finally {
 45             sqlSession.close();
 46         }
 47         
 48     }
 49     
 50     @Test
 51     public void testInsert() {
 52         
 53         MyUser user = new MyUser();
 54         user.setAge(90);
 55         user.setId(8);
 56         user.setUsername("tyu");
 57         user.setPassword("458");
 58         
 59         SqlSession sqlSession = getSessionFactory().openSession();  
 60         try {
 61             UserDao userDao = sqlSession.getMapper(UserDao.class);  
 62             userDao.insert(user);
 63             sqlSession.commit();
 64         
 65         }
 66         finally {
 67             sqlSession.close();
 68         }
 69         
 70     }
 71     
 72     @Test
 73     public void testFindAllUser() {
 74         
 75         SqlSession sqlSession = getSessionFactory().openSession();  
 76         try {
 77             UserDao userDao = sqlSession.getMapper(UserDao.class);  
 78             List<MyUser> list = userDao.findAllUser("3");
 79             for(MyUser user:list) {
 80                 System.out.println(user.toString());
 81             }
 82         
 83         }
 84         finally {
 85             sqlSession.close();
 86         }
 87         
 88     }
 89     
 90     @Test
 91     public void testGetUserById() {
 92         
 93         SqlSession sqlSession = getSessionFactory().openSession();  
 94         try {
 95             UserDao userDao = sqlSession.getMapper(UserDao.class);  
 96             MyUser user = userDao.getUserById(2); 
 97             System.out.println(user.toString());
 98         
 99         }
100         finally {
101             sqlSession.close();
102         }
103     
104     }
105 
106      //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
107     private static SqlSessionFactory getSessionFactory() {  
108         SqlSessionFactory sessionFactory = null;  
109         String resource = "configuration.xml";  
110         try {  
111             sessionFactory = new SqlSessionFactoryBuilder().build(Resources  
112                     .getResourceAsReader(resource));
113         } catch (IOException e) {  
114             e.printStackTrace();  
115         }  
116         return sessionFactory;  
117     }  
118     
119 }
View Code

 

posted @ 2019-06-10 16:45  捞的不谈  阅读(230)  评论(0编辑  收藏  举报