首先我们看下如何让spring与mybatis集成,我使用的是mysql数据库,建库建表语句如下:
drop database if exists demodb00;
CREATE database demodb00 DEFAULT CHARACTER SET utf8;
CREATE TABLE demodb00.user (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY id_UNIQUE (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
package net.aty.spring.entity;
public class UserEntity {
private int id;
private String name;
private int age;
public UserEntity() {
}
public UserEntity(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
package net.aty.spring.mapper;
import net.aty.spring.entity.UserEntity;
public interface UserMapper {
int insertOne(UserEntity user);
UserEntity selectByPk(int id);
}
<?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="net.aty.spring.mapper.UserMapper">
<insert id="insertOne" parameterType="net.aty.spring.entity.UserEntity">
INSERT INTO user(id, name,age) VALUE(#{id},#{name},#{age})
</insert>
<select id="selectByPk" resultType="net.aty.spring.entity.UserEntity" parameterType="java.lang.Integer">
select * from user where id=#{id}
</select>
</mapper>
<?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>
<!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
<settings>
<!-- 全局映射器启用缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<setting name="lazyLoadingEnabled" value="false"/>
<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="true"/>
<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true"/>
<!-- 允许使用列标签代替列名 -->
<setting name="useColumnLabel" value="true"/>
<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
<!-- <setting name="useGeneratedKeys" value="true" /> -->
<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
<setting name="autoMappingBehavior" value="FULL"/>
<!-- 对于批量更新操作缓存SQL以提高性能 -->
<setting name="defaultExecutorType" value="REUSE"/>
<!-- 数据库超过25000秒仍未响应则超时 -->
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
</configuration>