持续学习&持续更新中…
守破离
【Java从零到架构师第③季】【43】SpringBoot-MyBatis
- 引入依赖
- 数据源配置
- MyBatis配置
- 扫描DAO
- MyBatis主配置—XML
- MyBatis主配置—注解
- MyBatis主配置—application.yml
- starter的命名规范
- useGeneratedKeys
- 实例
- 项目结构
- Application
- MyBatisConfig
- application.yml 与 MyBatis映射文件
- mybatis-config.xml
- index.html
- controller
- service
- dao
- 参考
http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
<dependencies>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.3version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.2.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
dependencies>
数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/test_mybatis?serverTimezone=UTC
druid:
initial-size: 5
max-active: 10
MyBatis配置
扫描DAO
MyBatis主配置—XML
mybatis:
config-location: classpath:mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
configuration>
MyBatis主配置—注解
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer customizer() {
return (configuration) -> {
configuration.setMapUnderscoreToCamelCase(true);
};
}
}
MyBatis主配置—application.yml
mybatis:
configuration:
map-underscore-to-camel-case: true
starter的命名规范
https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
useGeneratedKeysuseGeneratedKeys直接写在映射文件中:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="programmer.lp.dao.SkillDao">
<insert id="save" parameterType="Skill"
useGeneratedKeys="true"
keyProperty="id">
INSERT INTO skill(name, level) VALUES (#{name}, #{level})
insert>
mapper>
实例
项目结构
Application
@SpringBootApplication
@MapperScan("programmer.lp.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
MyBatisConfig
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer customizer() {
return (configuration) -> {
configuration.setMapUnderscoreToCamelCase(true);
configuration.setUseGeneratedKeys(true);
};
}
}
application.yml 与 MyBatis映射文件
server:
servlet:
context-path: /mybatis
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/test_mybatis?serverTimezone=UTC
druid:
initial-size: 5
max-active: 10
mybatis:
type-aliases-package: programmer.lp.domain
# mapper-locations: classpath:mappers/*.xml
# config-location: classpath:mybatis-config.xml
configuration:
map-underscore-to-camel-case: true
use-generated-keys: true
或者直接将MyBatis-Mapper文件放到与dao相同的目录下:
方法一:
方法二:
pom.xml:
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="useGeneratedKeys" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
configuration>
index.html
DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Skilltitle>
head>
<body>
<div>
<a th:href="@{/skills/get(id=1)}" target="_blank">单个a>
div>
<div>
<a th:href="@{/skills/list}" target="_blank">列表a>
div>
<div>
保存
<form th:action="@{/skills/save}" method="post">
<input name="id" placeholder="id">
<input name="name" placeholder="name">
<input name="level" placeholder="level">
<button type="submit">保存button>
form>
div>
<div>
删除
<form th:action="@{/skills/remove}" method="post">
<input name="id" placeholder="id">
<button type="submit">删除button>
form>
div>
body>
html>
controller
@RestController
@RequestMapping("/skills")
public class SkillController {
@Autowired
private SkillService service;
@GetMapping("/list")
public List<Skill> list() {
return service.list();
}
@GetMapping("/get")
public Skill get(Integer id) {
return service.get(id);
}
@PostMapping("/save")
public String save(Skill skill) {
String[] msgs;
Integer id = skill.getId();
if (id != null && id > 0) {
msgs = new String[] {"更新成功", "更新失败"};
} else {
msgs = new String[] {"添加成功", "添加失败"};
}
return service.save(skill) ? msgs[0] + "_" + skill.getId() : msgs[1];
}
@PostMapping("/remove")
public String remove(Integer id) {
return service.remove(id) ? "删除成功" : "删除失败";
}
}
service
@Service
@Transactional
public class SkillServiceImpl implements SkillService {
@Autowired
private SkillDao dao;
@Override
public boolean save(Skill skill) {
System.out.println(skill.getId());
Integer id = skill.getId();
if (id == null || id < 1) {
return dao.save(skill);
}
return dao.update(skill);
}
@Override
@Transactional(readOnly = true)
public List<Skill> list() {
return dao.list();
}
@Override
@Transactional(readOnly = true)
public Skill get(Integer id) {
return dao.get(id);
}
@Override
public boolean remove(Integer id) {
return dao.remove(id);
}
}
public interface SkillService {
boolean save(Skill skill);
List<Skill> list();
Skill get(Integer id);
boolean remove(Integer id);
}
dao
public interface SkillDao {
boolean save(Skill skill);
boolean update(Skill skill);
boolean remove(Integer id);
@Select("SELECT * FROM skill")
List<Skill> list();
@Select("SELECT * FROM skill WHERE id = #{id}")
Skill get(Integer id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="programmer.lp.dao.SkillDao">
<insert id="save" parameterType="Skill"
useGeneratedKeys="true"
keyProperty="id">
INSERT INTO skill(name, level) VALUES (#{name}, #{level})
insert>
<update id="update" parameterType="Skill">
UPDATE skill SET name = #{name}, level = #{level} WHERE id = #{id}
update>
<delete id="remove" parameterType="int">
DELETE FROM skill WHERE id = #{id}
delete>
mapper>
参考
小码哥-李明杰: Java从0到架构师③进阶互联网架构师.
本文完,感谢您的关注支持!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)