mybatis-spring-boot-starter
、mysql
、druid
相关依赖。新建 web-app 项目,导入相关依赖
修改配置文件
server.port=8989
server.servlet.context-path=/springboot_day6
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.resources.static-locations=classpath:/templates/,classpath:/static/
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=1234
mybatis.mapper-locations=classpath:/com/rennen/mapper/*.xml
# Mapper 映射文件的存放地址
mybatis.type-aliases-package=com.rennen.entity
# 别名
入口类加上注解,用来做 Mapper 扫描
@SpringBootApplication
@MapperScan("com.rennen.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
建表和构建实体类
package com.rennen.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private String id;
private String name;
private Integer age;
private Date bir;
}
开发 DAO 接口
package com.rennen.dao;
import com.rennen.entity.User;
import java.util.List;
public interface UserDAO {
void save(User user);
List<User> findAll();
}
编写 Mapper 文件(IDEA 中添加模板)
<?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.baizhi.dao.ClazzDAO">
<select id="findAll" resultType="Clazz">
select * from t_clazz
</select>
</mapper>
开发 Service
//接口
public interface ClazzService {
List<Clazz> findAll();
}
//实现
@Service
@Transactional
public class ClazzServiceImpl implements ClazzService {
@Autowired
private ClazzDAO clazzDAO;
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<Clazz> findAll() {
return clazzDAO.findAll();
}
}