一、新建Spring Boot工程
(略,参考相关文章)
源码路径:https://gitee.com/sujianfeng/labcloud/tree/master/lab-mybatis
二、build.gradle加入依赖
主要是红色字体的部分
ependencies { implementation('org.springframework.boot:spring-boot-starter-data-jpa') implementation('org.springframework.boot:spring-boot-starter-web') implementation('de.codecentric:spring-boot-admin-starter-client') implementation('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2') implementation('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') implementation('com.alibaba:druid:1.1.0') runtimeOnly('mysql:mysql-connector-java') testImplementation('org.springframework.boot:spring-boot-starter-test') }
三、Spring Boot的启动类的注解
@SpringBootApplication
@MapperScan("com.labcloud.labmybatis.module.demo.dao") //用于自动生成dao层实现类(不用手动编写)
@EnableTransactionManagement //启动事务管理
@ComponentScan(basePackages = {"com.labcloud.labmybatis"}) //纳入事务管理包根路径
public class LabMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(LabMybatisApplication.class, args);
}
}
四、application.yml配置
server:
port: 8203
spring:
application:
name: lab-mybatis
datasource:
url: jdbc:mysql://localhost:3306/lab
username: root
password: 960720
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapperLocations: classpath:mapper/*.xml
type-Aliases-Package: com.labcloud.labmybatis.module.demo.entity
五、实现代码
(1)代码目录结构
(2)Controller层代码
@RestController
@EnableAutoConfiguration
@RequestMapping("/my-batis")
public class LabUserController {
@Resource
private LabUserService labUserService;
@RequestMapping(value = "/showUser", produces = "application/json;charset=UTF-8")
@ResponseBody
public LabUser showUser(HttpServletRequest request, Model model){
int userId = ConvertUtils.cInt(request.getParameter("id"));
LabUser user = this.labUserService.getUserById(userId);
return user;
}
}
(3)dao层接口定义
public interface LabUserDao {
int deleteByPrimaryKey(Integer id);
int insert(LabUser record);
int insertSelective(LabUser record);
LabUser selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(LabUser record);
int updateByPrimaryKey(LabUser record);
}
(4)实体定义
public class LabUser {
private Integer id;
private String userName;
private String password;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
(5)service接口定义
public interface ILabUserService {
public LabUser getUserById(int userId);
boolean addUser(LabUser record);
}
(6)service实现类
@Service
public class LabUserService implements ILabUserService {
@Resource
private LabUserDao labUserDao;
@Override
public LabUser getUserById(int labUserId) {
return labUserDao.selectByPrimaryKey(labUserId);
}
@Override
@Transactional
public boolean addUser(LabUser labUser) {
boolean result = false;
try {
labUserDao.insertSelective(labUser);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
(7)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="com.labcloud.labmybatis.module.demo.dao.LabUserDao" >
<resultMap id="BaseResultMap" type="com.labcloud.labmybatis.module.demo.entity.LabUser" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, username, password, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from lab_user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from lab_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.labcloud.labmybatis.module.demo.entity.LabUser" >
insert into lab_user (id, username, password,
age)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.labcloud.labmybatis.module.demo.entity.LabUser"
keyProperty="id" useGeneratedKeys="true"
>
insert into lab_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
username,
</if>
<if test="password != null" >
password,
</if>
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.labcloud.labmybatis.module.demo.entity.LabUser" >
update lab_user
<set >
<if test="userName != null" >
username = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.labcloud.labmybatis.module.demo.entity.LabUser" >
update lab_user
set username = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
(8)单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class DemoTest {
@Autowired
private LabUserService labUserService;
@Test
@Rollback(true)
public void test(){
LabUser labUser = new LabUser();
labUser.setUserName("test1");
boolean ok = labUserService.addUser(labUser);
Assert.isTrue(ok, "新增用户失败!");
LabUser labUser1 = labUserService.getUserById(labUser.getId());
Assert.isTrue(labUser1 != null, "查询用户失败!");
}
}
六、运行演示
(1)单元测试
在单元测试带密码DemoTest中,右键执行【Debug ‘’DemoTest】即可
(2)手动测试
结束!