16.MyBatis配置文件2

 

使用代理

1.删除Dao的impl包及其实现类

2.Mapper.xml与Dao接口

(1)<mapper namespace="[Dao接口的全限定名]">

(2)<insert id="[Dao接口中的对应方法名]">

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.course.dao;

import java.util.List;

import com.course.vo.User;

public interface UserDao {

public void addUser(User user);

public void updateUser(User user);

public void deleteUser(Integer id);

public User getUserById(Integer id);

public List<User> getAllUser();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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.course.dao.UserDao">
<insert id="addUser" parameterType="com.course.vo.User">
insert into user(name, age, address, birthday)
values(#{name}, #{age}, #{address}, #{birthday})
</insert>

<update id="updateUser" parameterType="com.course.vo.User">
update user set name=#{name}, age=#{age}, address=#{address}, birthday=#{birthday}
where id=#{id}
</update>

<delete id="deleteUser" parameterType="int">
delete from user
where id=#{val}
</delete>

<select id="getUserById" parameterType="int" resultType="com.course.vo.User">
select * from user where id=#{val}
</select>

<select id="getAllUser" resultType="com.course.vo.User">
select * from user
</select>
</mapper>

3.测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.course.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.course.dao.UserDao;
import com.course.util.MyBatisUtil;
import com.course.vo.User;

public class MainTest {

public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtil.openSqlSession();
// 得到UserDao的代理对象
UserDao userDao = sqlSession.getMapper(UserDao.class);

System.out.println(userDao);
// org.apache.ibatis.binding.MapperProxy@313ac989
System.out.println(userDao.getClass().getSimpleName());
// $Proxy3

List<User> userList = userDao.getAllUser();
for (User user : userList) {
System.out.println(user.toString());
}

MyBatisUtil.closeSqlSession(sqlSession);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/G:/eclipse/eclipse-2020-12/project/mybatis/03_mybatis_proxy/WebContent/WEB-INF/lib/mybatis-3.3.0.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
DEBUG [main] - Created connection 1262408432.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4b3ed2f0]
DEBUG [main] - ==> Preparing: select * from user
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 10
User [id=1, name=user1, age=10, address=address1, birthday=Fri Aug 13 12:35:22 CST 2021]
User [id=2, name=user2, age=10, address=address2, birthday=Fri Aug 13 16:51:11 CST 2021]
User [id=4, name=user1, age=10, address=address1, birthday=Fri Aug 13 16:55:22 CST 2021]
User [id=5, name=user2, age=10, address=address2, birthday=Fri Aug 13 16:55:22 CST 2021]
User [id=7, name=user1, age=10, address=address1, birthday=Fri Aug 13 16:57:01 CST 2021]
User [id=8, name=user2, age=10, address=address2, birthday=Fri Aug 13 16:57:01 CST 2021]
User [id=9, name=user3, age=10, address=address3, birthday=Fri Aug 13 16:57:01 CST 2021]
User [id=11, name=user11, age=10, address=address11, birthday=Fri Aug 13 16:58:27 CST 2021]
User [id=12, name=user12, age=10, address=address2, birthday=Mon Aug 16 15:54:29 CST 2021]
User [id=14, name=user3, age=10, address=address3, birthday=Mon Aug 16 15:53:30 CST 2021]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4b3ed2f0]
DEBUG [main] - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4b3ed2f0]
DEBUG [main] - Returned connection 1262408432 to pool.

<mapper namespace="">与接口的全限定名不对应:

1
2
3
4
5
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com.course.dao.UserDao is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:675)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:250)
at com.course.test.MainTest.main(MainTest.java:15)

若Mapper.xml的节点id与接口中的方法名不对应:

1
2
3
4
5
6
7
Exception in thread "main" org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.course.dao.UserDao.getUserById
at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:196)
at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:44)
at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:59)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
at com.sun.proxy.$Proxy3.getUserById(Unknown Source)
at com.course.test.MainTest.main(MainTest.java:23)

Mapper.xml详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?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.course.dao.UserDao">
<!--
1. id: 节点的唯一标识,对应接口中的方法名,不能重复
2. parameterType: 参数类型
3. parameterMap: 参数map类型
4. useGeneratedKeys="true": 是否使用自动增长,默认为true
说明: parameterType和parameterMap只能存在一个
-->

<!--
<insert id="addUser" parameterType="com.course.vo.User" >
insert into user(name, age, address, birthday)
values(#{name}, #{age}, #{address}, #{birthday})
</insert>
-->
<parameterMap type="com.course.vo.User" id="userVO">
<parameter property="name" javaType="java.lang.String"/>
<parameter property="address" javaType="java.lang.String"/>
</parameterMap>
<insert id="addUser" parameterMap="userVO">
insert into user(name, age, address, birthday)
values(#{name}, #{age}, #{address}, #{birthday})
</insert>

<!--
1. id: 节点的唯一标识,对应接口中的方法名,不能重复
2. parameterType: 参数类型
-->
<update id="updateUser" parameterType="com.course.vo.User">
update user set name=#{name}, age=#{age}, address=#{address}, birthday=#{birthday}
where id=#{id}
</update>

<!--
1. id: 节点的唯一标识,对应接口中的方法名,不能重复
2. parameterType: 参数类型,如果是基本数据类型或者String,可以不配置parameterType
-->
<delete id="deleteUser" parameterType="int">
delete from user
where id=#{val}
</delete>

<!--
1. id: 节点的唯一标识,对应接口中的方法名,不能重复
2. parameterType: 参数类型
3. resultType: 返回值的类型
-->
<select id="getUserById" parameterType="int" resultType="com.course.vo.User">
select * from user where id=#{val}
</select>

<!--
1. id: 节点的唯一标识,对应接口中的方法名,不能重复
2. resultMap: 如果查询的结果集字段名与实体类属性名不同,可以使用resultMap
3. resultType: 返回值的类型,查询的结果集字段名与实体类属性名相同
说明: resultType和resultMap只能存在一个
-->
<!--
<select id="getAllUser" resultType="com.course.vo.User">
select
id as userId,
name as userName,
age as userAge,
address as addr,
birthday as birth
from user
</select>
-->
<resultMap type="com.course.vo.User" id="userVO">
<id property="id" column="userId"/>
<result property="name" column="userName"/>
<result property="age" column="userAge"/>
<result property="address" column="addr"/>
<result property="birthday" column="birth"/>
</resultMap>
<select id="getAllUser" resultMap="userVO">
select
id as userId,
name as userName,
age as userAge,
address as addr,
birthday as birth
from user
</select>
</mapper>

parameterMap和resultMap的id可以相同

配置别名

mybatis.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!--
The content of element type "configuration" must match
"(properties?,settings?,typeAliases?,typeHandlers?,
objectFactory?,objectWrapperFactory?,reflectorFactory?,
plugins?,environments?,databaseIdProvider?,mappers?)".

<properties></properties>
<typeAliases></typeAliases>
<plugins></plugins>
<environments></environments>
<mappers></mappers>
-->

<!-- 配置类的别名 -->
<!--
<typeAliases>
一个一个配置
<typeAlias type="com.course.vo.User" alias="User"/>
</typeAliases>
-->
<typeAliases>
<!-- 批量配置包下所有的实体类 -->
<package name="com.course.vo"/>
</typeAliases>
</configuration>

mapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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.course.dao.UserDao">

<select id="getAllUser" resultType="User">
select
id,
name,
age,
address,
birthday
from user
</select>

</mapper>

mybatis占位符的处理

1,占位符一:#{xxx}

PreparedStatement预编译sql语句

xxx表达式的写法

  • 参数类型为javabean类,xxx表达式必须和javabean中属性对应的get方法名字一样
  • 参数类型为简单类型,xxx表达式随表写,保持和参数的名字一致
1
2
3
4
5
6
<mapper namespace="com.course.dao.UserDao">
<insert id="addUser" parameterType="com.course.vo.User" >
insert into user(name, age, address, birthday)
values(#{name}, #{age}, #{address}, #{birthday})
</insert>
</mapper>
1
2
3
DEBUG [main] - ==>  Preparing: insert into user(name, age, address, birthday) values(?, ?, ?, ?) 
DEBUG [main] - ==> Parameters: user18(String), 10(Integer), address18(String), 2021-08-20 17:41:03.196(Timestamp)
DEBUG [main] - <== Updates: 1

2,占位符二:${xxx}

Statement拼接sql语句

xxx表达式的写法

  • 参数类型为javabean类,xxx表达式必须和javabean中属性对应的get方法名字一样
  • 参数类型为简单类型,xxx表达式执行只能写${value}
1
2
3
4
5
6
<mapper namespace="com.course.dao.UserDao">
<insert id="addUser" parameterType="com.course.vo.User" >
insert into user(name, age, address)
values('${name}', ${age}, '${address}')
</insert>
</mapper>
1
2
3
DEBUG [main] - ==>  Preparing: insert into user(name, age, address) values('user18', 10, 'address18') 
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Updates: 1
1
2
3
4
5
<mapper namespace="com.course.dao.UserDao">
<select id="getUserById" parameterType="int" resultType="com.course.vo.User">
select * from user where id=${val}
</select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'val' in 'class java.lang.Integer'
### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'val' in 'class java.lang.Integer'
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:122)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:113)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:73)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:69)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
at com.sun.proxy.$Proxy3.getUserById(Unknown Source)
at com.course.test.MainTest.main(MainTest.java:32)
Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'val' in 'class java.lang.Integer'
at org.apache.ibatis.reflection.Reflector.getGetInvoker(Reflector.java:381)
at org.apache.ibatis.reflection.MetaClass.getGetInvoker(MetaClass.java:164)
1
2
3
4
5
<mapper namespace="com.course.dao.UserDao">
<select id="getUserById" parameterType="int" resultType="com.course.vo.User">
select * from user where id=${value}
</select>
</mapper>
1
2
3
4
DEBUG [main] - ==>  Preparing: select * from user where id=12 
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 1
User [id=12, name=user12, age=10, address=address2, birthday=Mon Aug 16 15:54:29 CST 2021]