JAVA框架 Mybaits

 注意:我们在resultType中,对于selectlist方法也是projo类。resultType参数的含义是list的泛型的类型。

一:jar包下载:

https://github.com/mybatis/mybatis-3/releases?after=mybatis-3.2.8

我使用的版本是3.2,7

二、创建项目 导入核心jar包和依赖的jar包。

pom.xml文件内容:

 1   <properties>
 2     <!--需要注意还珠格格编译器的版本要和jdk版本一直-->
 3     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 4     <maven.compiler.source>1.8</maven.compiler.source>
 5     <maven.compiler.target>1.8</maven.compiler.target>
 6   </properties>
 7 
 8   <dependencies>
 9     <dependency>
10       <groupId>org.slf4j</groupId>
11       <artifactId>slf4j-log4j12</artifactId>
12       <version>1.7.5</version>
13     </dependency>
14     <dependency>
15       <groupId>org.slf4j</groupId>
16       <artifactId>slf4j-api</artifactId>
17       <version>1.7.5</version>
18     </dependency>
19     <dependency>
20       <groupId>org.apache.logging.log4j</groupId>
21       <artifactId>log4j-core</artifactId>
22       <version>2.0.2</version>
23     </dependency>
24     <dependency>
25       <groupId>org.apache.logging.log4j</groupId>
26       <artifactId>log4j-api</artifactId>
27       <version>2.0.2</version>
28     </dependency>
29     <dependency>
30       <groupId>mysql</groupId>
31       <artifactId>mysql-connector-java</artifactId>
32       <version>5.1.34</version>
33     </dependency>
34     <dependency>
35       <groupId>log4j</groupId>
36       <artifactId>log4j</artifactId>
37       <version>1.2.17</version>
38     </dependency>
39     <dependency>
40       <groupId>org.javassist</groupId>
41       <artifactId>javassist</artifactId>
42       <version>3.16.1-GA</version>
43     </dependency>
44     <dependency>
45       <groupId>commons-logging</groupId>
46       <artifactId>commons-logging</artifactId>
47       <version>1.1.1</version>
48     </dependency>
49     <dependency>
50       <groupId>cglib</groupId>
51       <artifactId>cglib</artifactId>
52       <version>2.2.2</version>
53     </dependency>
54     <dependency>
55       <groupId>asm</groupId>
56       <artifactId>asm</artifactId>
57       <version>3.3.1</version>
58     </dependency>
59     <dependency>
60       <groupId>org.mybatis</groupId>
61       <artifactId>mybatis</artifactId>
62       <version>3.2.7</version>
63     </dependency>
64     <dependency>
65       <groupId>junit</groupId>
66       <artifactId>junit</artifactId>
67       <version>4.11</version>
68       <scope>test</scope>
69     </dependency>
70     <dependency>
71       <groupId>org.junit.jupiter</groupId>
72       <artifactId>junit-jupiter-api</artifactId>
73       <version>RELEASE</version>
74     </dependency>
75   </dependencies>

 mybaits的配置文件说明:

其中SqlMapConfig.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     <!-- 和spring整合后 environments配置将废除-->
 7     <environments default="development">
 8         <environment id="development">
 9             <!-- 使用jdbc事务管理-->
10             <transactionManager type="JDBC" />
11             <!-- 数据库连接池 mybaits自带的连接池-->
12             <dataSource type="POOLED">
13                 <property name="driver" value="com.mysql.jdbc.Driver" />
14                 <property name="url" value="jdbc:mysql://localhost:3306/day_spring?characterEncoding=utf-8" />
15                 <property name="username" value="root" />
16                 <property name="password" value="root" />
17             </dataSource>
18         </environment>
19     </environments>
20     <mappers >
21         <mapper resource="account.xml" />
22     </mappers>
23 </configuration> 

account.xml是子配置文件。包含一些sql语句的查询。内容如下:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="test1"><!--namespace起到sql隔离的作用-->
 6     <select id="FindAccountById" resultType="jd.com.mybaitstest.account" parameterType="java.lang.Integer" >
 7         SELECT * FROM t_account WHERE id=#{id};
 8     </select>
 9     <!--注意like拼接的需要使用#{value} 必须是value。-->
10     <select id="FindUsernameByNanme" resultType="jd.com.mybaitstest.account" parameterType="java.lang.String" >
11 
12         SELECT * FROM  t_account WHERE NAME LIKE '%${value}%';
13     </select>
14     <!--插入语句 注意 这里我们插入值是account对象 注意的是这里的占位符的名字是account的属性-->
15 
16     <insert id="InsertVal" parameterType="jd.com.mybaitstest.account">
17         <!-- id返回的设置  标签selectkey 属性keyproperty表示:account的属性名,order 获取是插入的前(before)还是后(after)返回的数据类型-->
18         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
19             <!--通过数据库的内置函数SELECT LAST_INSERT_ID()获取插入的语句返回的id的值。mybaits帮我们设置到我们对象中。并设置属性是id-->
20             SELECT LAST_INSERT_ID();
21         </selectKey>
22         INSERT INTO t_account(NAME ,money) VALUES(#{name},#{money});
23     </insert>
24     <delete id="DeletAccoutnById" parameterType="int" >
25         DELETE FROM t_account WHERE id=#{id};
26     </delete>
27     <update id="UpdateById" parameterType="jd.com.mybaitstest.account"  >
28         UPDATE t_account SET money=#{money} WHERE id=#{id};
29     </update>
30 </mapper>

mybaits的简单的增删改查:

 1 package jd.com.mybaitstest;
 2 
 3 import org.apache.ibatis.io.Resources;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.apache.ibatis.session.SqlSessionFactory;
 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 7 import org.junit.jupiter.api.Test;
 8 
 9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.util.List;
12 
13 public class testmyba {
14 
15 
16     @Test
17     public void  testdemo1() throws IOException {
18         //查询单条数据
19         String resouce="SqlMapConfig.xml";
20         InputStream inputStream= Resources.getResourceAsStream(resouce);
21         SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
22         SqlSession sqlSession=sqlSessionFactory.openSession();
23         account ac=sqlSession.selectOne("test1.FindAccountById",2);
24         System.out.println(ac);
25     }
26     @Test
27     public  void  testdemo2() throws IOException {
28         String resource="SqlMapConfig.xml";
29         //获取主配置文件流
30         InputStream inp=Resources.getResourceAsStream(resource);
31         //创建数据库回话
32         SqlSession sqlSession=new SqlSessionFactoryBuilder().build(inp).openSession();
33         List<account> list=sqlSession.selectList("test1.FindUsernameByNanme","ok");
34         System.out.println(list);
35 
36     }
37     @Test
38     public  void  testInsertdemo() throws IOException {
39         String resource="SqlMapConfig.xml";
40         InputStream inp=Resources.getResourceAsStream(resource);
41         SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inp);
42         SqlSession sqlSession=sqlSessionFactory.openSession();
43         account ac=new account();
44         ac.setMoney(234);
45         ac.setName("oko");
46         sqlSession.insert("test1.InsertVal",ac);
47         //在主配置文件中配置了事务。需要commit 才能生效。
48         sqlSession.commit();
49         System.out.println(ac.getId());
50     }
51     @Test
52     public  void  deleteDemo() throws IOException {
53         String resource="SqlMapConfig.xml";
54         InputStream inp=Resources.getResourceAsStream(resource);
55         SqlSession sqlSession=new SqlSessionFactoryBuilder().build(inp).openSession();
56         sqlSession.delete("test1.DeletAccoutnById",2);
57         sqlSession.commit();
58     }
59     @Test
60     public  void  updateById() throws IOException {
61         String resource="SqlMapConfig.xml";
62         InputStream inp=Resources.getResourceAsStream(resource);
63         SqlSession sqlSession=new SqlSessionFactoryBuilder().build(inp).openSession();
64         account ac=new account();
65         ac.setMoney(100100);
66         ac.setId(3);
67         sqlSession.update("test1.UpdateById",ac);
68         sqlSession.commit();
69     }
70 }

 注意:我们使用sqlsessionfactory来获取sqlsession,其中通过selelct、delete、update、insert等方法进行进行增删改查。

其中方法内的参数delete(“子配置文件的中namespace.语句id值”,参数)。也就是说我们 通过子配置文件的namespace值和语句中的id值来唯一确定执行那个sql语句。

子配置文件的占位符:

占位符:作用是底层调用jdbc的时候,使用preparestatment的时候,进行sql的占位符一一对应,传入参数。

#{}占位符:

  如果传入的是基本的类型那么#{}中的变量名字可以随便写。

  如果传入的是pojo类的时候,那么#{}的变量名字必须要和pojo类的属性名字一致。

${}拼接符:

  如果传入的是基本的类型那么${}中的变量名称必须为value。

  如果传入的是pojo类的时候,那么${}必须是和pojo的类的属性名称一致。

  注意${}拼接符,有可能造成sql注入,解决方法可以在用户输入的页面进行校验不可输入sql关键字,不可以输入空格。或者后端做校验验证。

主键返回

  主键一般是自增或者使用uuid。通过数据库的内置函数获取插入值之后的主键值。

1、uuid:

 1 <insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User">
 2 
 3 <selectKey resultType="java.lang.String" order="BEFORE"
 4 
 5 keyProperty="id">
 6 
 7 select uuid()
 8 
 9 </selectKey>
10 
11 insert into user(id,username,birthday,sex,address)
12 
13        values(#{id},#{username},#{birthday},#{sex},#{address})
14 
15 </insert>

注意这里使用的order是“BEFORE”,因为uuid需要我们提前生成 在插入数据库所以在insert语句之前执行。

2、自增主键:

1     <insert id="InsertVal" parameterType="jd.com.mybaitstest.account">
2         <!-- id返回的设置  标签selectkey 属性keyproperty表示:account的属性名,order 获取是插入的前(before)还是后(after)返回的数据类型-->
3         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
4             <!--通过数据库的内置函数SELECT LAST_INSERT_ID()获取插入的语句返回的id的值。mybaits帮我们设置到我们对象中。并设置属性是id-->
5             SELECT LAST_INSERT_ID();
6         </selectKey>
7         INSERT INTO t_account(NAME ,money) VALUES(#{name},#{money});
8     </insert>

三、原生dao层编写:

dao层:

 interface:

1 package jd.com.dao;
2 
3 import jd.com.mybaitstest.account;
4 
5 public interface acci {
6     void selecDemo(int i);
7     void  updateDemo(account ac);
8 }

implement class:

 1 package jd.com.dao;
 2 
 3 
 4 import jd.com.Utils.session;
 5 import jd.com.mybaitstest.account;
 6 import org.apache.ibatis.session.SqlSession;
 7 
 8 public class acciImpl implements  acci {
 9     @Override
10     public void selecDemo(int i) {
11         SqlSession sqlSession=session.getSession();
12         account ac=sqlSession.selectOne("test1.FindAccountById",i);
13         System.out.println(ac);
14     }
15 
16     @Override
17     public void updateDemo(account ac) {
18         SqlSession sqlSession=session.getSession();
19         sqlSession.update("test1.UpdateById",ac);
20         sqlSession.commit();
21     }
22 }

测试程序:

 1 package jd.com.dao;
 2 
 3 import jd.com.mybaitstest.account;
 4 import org.junit.jupiter.api.Test;
 5 
 6 public class testdemodap {
 7 
 8     @Test
 9     public  void  testdemo1(){
10         acciImpl ac1=new acciImpl();
11         ac1.selecDemo(3);
12         account ac=new account();
13         ac.setMoney(3322);
14         ac.setName("poppp");
15         ac.setId(9);
16         ac1.updateDemo(ac);
17     }
18 }

 

原文地址:https://www.cnblogs.com/evilliu/p/8927066.html