1.mapper动态代理开发注意事项
- 接口方法名需要与mapper.xml的要调用的SQL语句的ID一致
- 接口的形参类型需要与mapper.xml parameterType类型一致
- 接口的返回值类型要与mapper.xml resultType一致
- mapper.xml中的namespace要与接口的全包名一致
- mapper动态代理中,selectList/selectOne根据返回值类型自动选择
2.配置文件
sqlMapConfig.xml
<?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>
<!-- 读取数据库配置文件 -->
<properties resource="db.properties" />
<!-- 配置环境-默认环境id为MySQL -->
<environments default="MySQL">
<environment id="MySQL">
<!-- 使用JDBC事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 将sql映射文件注册到全局配置文件中 -->
<mappers>
<mapper resource="pers/goodwin/mybatis/mapper/UserMapper.xml" />
</mappers>
</configuration>
UserMapper.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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
-->
<mapper namespace="pers.goodwin.mybatis.mapper.UserMapper">
<select id="selectUserById" parameterType="Integer" resultType="pers.goodwin.mybatis.bean.User">
select * from t_user where u_id = #{id}
</select>
<!-- #{}占位符 尽量使用占位符来解决问题 -->
<!-- ${}字符串拼接 容易产生SQL注入问题 -->
<select id="selectUserByName" parameterType="String" resultType="pers.goodwin.mybatis.bean.User">
<!-- select * from t_user where u_username like '%${value}%' -->
select * from t_user where u_username like "%"#{id}"%"
</select>
<!-- 添加用户 -->
<insert id="insertUser" parameterType="pers.goodwin.mybatis.bean.User">
insert into t_user values (null, #{u_username}, #{u_password}, #{u_gender}, #{u_cid})
</insert>
<update id="updateUser" parameterType="pers.goodwin.mybatis.bean.User">
update t_user set u_username = #{u_username} where u_id = #{u_id}
</update>
<delete id="deleteUserById" parameterType="Integer">
delete from t_user where u_id = #{id}
</delete>
</mapper>
db.properties
#database configuration information
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_ssm_mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456
log4j.properties
#Global configuration
log4j.rootLogger=DEBUG,stdout
#Console configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.layout.ConversionPattern=%5p [%t] - %m%n
3.测试示例
3.1 User.java
package pers.goodwin.mybatis.bean;
/**
* @author goodwin
*
*/
public class User {
private Integer u_id;
private String u_username;
private String u_password;
private Integer u_gender;
private Integer u_cid;
public Integer getU_id() {
return u_id;
}
public void setU_id(Integer u_id) {
this.u_id = u_id;
}
public String getU_username() {
return u_username;
}
public void setU_username(String u_username) {
this.u_username = u_username;
}
public String getU_password() {
return u_password;
}
public void setU_password(String u_password) {
this.u_password = u_password;
}
public Integer getU_gender() {
return u_gender;
}
public void setU_gender(Integer u_gender) {
this.u_gender = u_gender;
}
public Integer getU_cid() {
return u_cid;
}
public void setU_cid(Integer u_cid) {
this.u_cid = u_cid;
}
@Override
public String toString() {
return "User [u_id=" + u_id + ", u_username=" + u_username + ", u_password=" + u_password + ", u_gender="
+ u_gender + ", u_cid=" + u_cid + "]";
}
}
3.2 UserMapper.java
package pers.goodwin.mybatis.mapper;
import java.util.List;
import pers.goodwin.mybatis.bean.User;
public interface UserMapper {
//mapper动态代理开发注意事项
//1.接口方法名需要与mapper.xml的要调用的SQL语句的ID一致
//2.接口的形参类型需要与mapper.xml parameterType类型一致
//3.接口的返回值类型要与mapper.xml resultType一致
//4.mapper.xml中的namespace要与接口的全包名一致
//5.mapper动态代理中,selectList/selectOne根据返回值类型自动选择
//通过ID查询一个用户
public User selectUserById(Integer id);
//模糊查询
public List<User> selectUserByName(String name);
}
3.3 MapperTest.java
package pers.goodwin.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
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 org.junit.Test;
import pers.goodwin.mybatis.bean.User;
import pers.goodwin.mybatis.mapper.UserMapper;
public class MapperTest {
@Test
public void Test1() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder ssb = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = ssb.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
}
@Test
public void Test2() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder ssb = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = ssb.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUserByName("王");
for (User user : userList) {
System.out.println(user);
}
}
}
3.4 测试结果
Test1
Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2003891312.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@7770f470]
==> Preparing: select * from t_user where u_id = ?
==> Parameters: 1(Integer)
<== Total: 1
User [u_id=1, u_username=老王, u_password=12345, u_gender=0, u_cid=1]
Test2
Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2003891312.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@7770f470]
==> Preparing: select * from t_user where u_username like "%"?"%"
==> Parameters: 王(String)
<== Total: 3
User [u_id=1, u_username=老王, u_password=12345, u_gender=0, u_cid=1]
User [u_id=2, u_username=王五, u_password=123, u_gender=1, u_cid=3]
User [u_id=5, u_username=王八, u_password=3232, u_gender=0, u_cid=4]