The use of the java mybatis mybatis operation implemented crud

Directory Structure:

 

1. Packaging mybatis of tools:

MybatisUtil.java

public class MybatisUtil {
    private static SqlSessionFactory getSqlSessionFactory() throws IOException{
        Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
        return  new SqlSessionFactoryBuilder().build(reader);
    }
    public static SqlSession getSqlSession() throws IOException{
        //填写参数 true表示事务自动提交
        return getSqlSessionFactory().openSession(true);
    }
}

2.vo class

User.java

 1 public class User implements Serializable{
 2     private int id;
 3     private String name;
 4     private int age;
 5     public int getId() {
 6         return id;
 7     }
 8     public void setId(int id) {
 9         this.id = id;
10     }
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17     public int getAge() {
18         return age;
19     }
20     public void setAge(int age) {
21         this.age = age;
22     }
23     @Override
24     public String toString() {
25         return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
26     }
27 }
View Code

3. mapping file

UserMapper.xml

<? xml Version = "1.0" encoding = "UTF-8"?> 
<! DOCTYPE Mapper 
the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" 
"http://mybatis.org/dtd/mybatis mapper.dtd--3 "> 
<-!  
    namespace is used to specify the namespace mapping file, where you can find all the space under by namespace 
    SQL statement mapping. namespace are usually named and should be mapped files are located [package name + map file name]
  -> 
<Mapper namespace = "cn.sxt.vo.UserMapper"> 
    <the SELECT the above mentioned id = "findAll" resultType = "the User"> 
        the SELECT * from t_user
     </ the SELECT> 

    <! - the SELECT statement used to write sql query id is unique in the same namespace. 
        parameterType used to specify the type of the parameter 
        # {id} placeholder will be populated with the input parameters. Recommendations and parameter names for the same 
        resultType used to specify a return value type
      ->
    <SELECT ID = "selectUser" the parameterType = "int" = the resultType "the User"> 
        SELECT * WHERE from T_USER ID = # {ID}
     </ SELECT> 
    <-! INSERT statement is used to map the insertion 
        useGeneratedKeys indication from the primary key is true by policy 
        parameterType used to specify the type of parameter 
        placeholder property name is the name of the parameter, and to provide a GET / SET method
     -> 
    <INSERT ID = "insertUser" useGeneratedKeys = "to true" parameterType = "the User"> 
        INSERT INTO T_USER (name, Age) values (# {name}, Age {#})
     </ INSERT> 
    <-! delete statement specifies delete -> 
    <delete ID = "deleteUser" the parameterType = "int">
        WHERE ID from T_USER Delete = # {ID}
    </delete> 
    <-! update statement to specify Update ->
    <update id="updateUser" parameterType="User">
        update t_user set name=#{name},age=#{age} where id=#{id}
    </update>
</mapper>

 4. core profile

mybatis.cfg.xml

<? xml Version = "1.0" encoding = "UTF-8"?> 
<! DOCTYPE the Configuration 
the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN" 
"http://mybatis.org/dtd/mybatis config.dtd--3 "> 
<Configuration> 
    <-! they are externalized, alternative properties . Can be disposed in a typical Java properties file, or by 
        configuration elements of the sub-elements of the properties -> 
    < properties Resource = " the jdbc.properties "> </ properties> 
    <-! Alias is a short type of Java name. To set the alias -> 
    <typeAliases> 
        <-! All classes alias the package for a specified, the default alias for the class name -> 
        < Package name = "cn.sxt.vo" /> 
        <!<typeAlias of the type = "cn.sxt.vo.User" Alias = "the User" /> 
        -> 
    </ typeAliases> 
    <-! MyBatis can configure multiple sets of operating environment, which helps you to map to multiple SQL databases on. For example, in your 
    development, test and production environments, you may have a different configuration. 
        pointing to default environment used by default
      -> 
    <Environments default = "Development"> 
        <Environment the above mentioned id = "Development"> 
            <-!  
                JDBC - This configuration directly submitted JDBC and rollback capabilities. It relies on data obtained from a source connected to manage the 
                affairs of the life cycle. 
                • MANAGED - This configuration is basically doing nothing. It never commit or roll back a transaction connected. But let 
                container (such as: Spring or J2EE application server) to manage the life cycle of a transaction. 
             -> 
            <the transactionManager type = "the JDBC" /> 
                UNPOOLED - this type of data source implementation simply opened and closed every time the connection needed. 
                POOLED - to achieve this cached data source JDBC connection object used to avoid each time you create a new database when the initial connection 
                and authentication to speed up the response program. Concurrent WEB applications often get quick response to this approach. 
                JNDI - this configuration is to prepare the data source and the image Spring or application server to the external or internal configuration data 
                for use with a source container, and then refer to it in the context JNDI. 
             -> 
            <type the dataSource = "the POOLED"> 
                <Property name = "Driver" value = "$ { Driver }" /> 
                <Property name = "URL" value = "$ { URL }" /> 
                <Property name = " username "value =" $ { username } "/> 
                <Property name =" password "
            </ dataSource>
        </ Environment> 
    </ Environments> 
    <mappers> 
        <-! SQL statement mapping file configuration -> 
        <Resource Mapper = "CN / SXT / VO / UserMapper.xml" /> 
    </ mappers> 
</ the Configuration>

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=1111

5. Test

MybatisTest.java

public  class MybatisTest { 
    @Test 
    public  void testAdd () throws IOException { 
        the User User = new new the User (); 
        user.setName ( "Andy" ); 
        user.setAge ( 55 ); 
        the SqlSession the session = MybatisUtil.getSqlSession ();
         // add the return value is affected by deletion of the number of rows 
        session.insert ( "cn.sxt.vo.UserMapper.insertUser" , User); 
        Session.close (); 
    } 
    @Test 
    public  void testUpdate () throws IOException { 
        the SqlSession the session= MybatisUtil.getSqlSession();
        User user=session.selectOne("cn.sxt.vo.UserMapper.selectUser", 1);
        user.setName("彰五金");
        session.update("cn.sxt.vo.UserMapper.updateUser",user);
        session.close();
    }
    @Test
    public void testDelete() throws IOException{
        SqlSession session = MybatisUtil.getSqlSession();
        session.delete("cn.sxt.vo.UserMapper.deleteUser", 3);
        session.close();
    }
    @Test
    public void testFindAll() throws IOException{
        SqlSession session = MybatisUtil.getSqlSession();
        List<User> list = session.selectList("cn.sxt.vo.UserMapper.findAll");
        for(User u:list){
            System.out.println(u);
        }
        session.close();
    }
}

 

Guess you like

Origin www.cnblogs.com/Vincent-yuan/p/11297342.html