springboot使⽤Mybatis(xml和注解)全解析
刚毕业的第⼀份⼯作是 java 开发,项⽬中需要⽤到 mybatis,特此记录学习过程,这只是⼀个简单 demo,mybatis ⽤法很多不可能全部写出来,有更复杂的需求建议查看 mybatis 的官⽅中⽂⽂档,。下⾯时项⽬环境/版本。
开发⼯具:IDEA
jdk 版本:1.8
springboot 版本:2.03
其他依赖版本见下⾯ l:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId&le</groupId>
<artifactId>mybatis-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatis-test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
&porting.outputEncoding>UTF-8</porting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis依赖 -->
<dependency>
<groupId&batis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--alibaba连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--分页依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.创建项⽬
使⽤ idea 中的 spring initializr ⽣成 maven 项⽬,项⽬命令为 mybatis-test,选择 web,mysql,mybatis 依赖,即可成功。(详细过程不赘述,如有需要学习 springboot 创建过程,可参考。
然后依照上⾯的 pom ⽂件,补齐缺少的依赖。接着创建包 entity,service 和 mybatis 映射⽂件夹 mapper,创建。为了⽅便配置将application.properties 改成 l。由于我们时 REST 接⼝,故不需要 static 和 templates ⽬录。修改完毕后的项⽬结构如下:
修改启动类,增加@MapperScan("batistest.dao"),以⾃动扫描 dao ⽬录,避免每个 dao 都⼿动加@Mapper注解。代码如下:
@SpringBootApplication
@MapperScan("batistest.dao")
public class MybatisTestApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisTestApplication.class, args);
}
}
修改 l,配置项⽬,代码如下:
mybatis:
#对应实体类路径
type-aliases-package: ity
#对应mapper映射⽂件路径
mapper-locations: classpath:mapper/*.xml
#pagehelper物理分页配置
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
returnPageInfo: check
server:
port: 8081
spring:
datasource:
name: mysqlTest
type: com.alibaba.druid.pool.DruidDataSource
#druid连接池相关配置
druid:
#监控拦截统计的filters
filters: stat
driver-class-name: sql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: 123456
#配置初始化⼤⼩,最⼩,最⼤
initial-size: 1
min-idle: 1
max-active: 20
#获取连接等待超时时间
max-wait: 6000
#间隔多久检测⼀次需要关闭的空闲连接
time-between-eviction-runs-millis: 60000
#⼀个连接在池中的最⼩⽣存时间
min-evictable-idle-time-millis: 300000
#打开PSCache,并指定每个连接上PSCache的⼤⼩。oracle设置为true,mysql设置为false。分库分表设置较多推荐设置 pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
http:
encoding:
charset: utf-8
enabled: true
2.编写代码
⾸先创建数据表,sql 语句如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` tinyint(4) NOT NULL DEFAULT '0',
`password` varchar(255) NOT NULL DEFAULT '123456',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
然后在 entity 包中创建实体类 User.java
public class User {
private int id;
private String name;
private int age;
private String password;
public User(int id, String name, int age, String password) {
this.id = id;
this.name = name;
this.age = age;
this.password = password;
}
public User(){}
//getter setter⾃⾏添加
}
在 dao 包下创建 UserDao.java
public interface UserDao {
//插⼊⽤户
int insert(User user);
//根据id查询
User selectById(String id);
//查询所有
List<User> selectAll();
}
在 mapper ⽂件夹下创建 l,具体的 xml 编写⽅法查看⽂⾸的官⽅⽂档。
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="batistest.dao.UserDao">
<sql id="BASE_TABLE">
user
</sql>
<sql id="BASE_COLUMN">
id,name,age,password
</sql>
<insert id="insert" parameterType="ity.User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO <include refid="BASE_TABLE"/>
<trim prefix="(" suffix=")" suffixOverrides=",">
name,password,
<if test="age!=null">
age
</if>
</trim>
<trim prefix=" VALUE(" suffix=")" suffixOverrides=",">
#{name,jdbcType=VARCHAR},#{password},
<if test="age!=null">
#{age}
</if>
</trim>
</insert>
<select id="selectById" resultType="ity.User">
select
<include refid="BASE_COLUMN"/>
from
<include refid="BASE_TABLE"/>
where id=#{id}
</select>
<select id="selectAll" resultType="ity.User">
select
<include refid="BASE_COLUMN"/>
from
<include refid="BASE_TABLE"/>
</select>
</mapper>
⾄此使⽤ mybatis 的代码编写完了,之后要⽤时调⽤ dao 接⼝中的⽅法即可。
3.测试
我们通过编写 service,controller 然后使⽤ postman 进⾏测试。
⾸先编写 UserService.java,代码如下:
@Component
public class UserService {
@Autowired
private UserDao userDao;
public User getByUserId(String id){
return userDao.selectById(id);
}
/
/获取全部⽤户
public List<User> getAll(){
return userDao.selectAll();
}
//测试分页
public PageInfo<User> getAll(int pageNum,int pageSize){
PageHelper.startPage(pageNum,pageSize);
List<User> users = userDao.selectAll();
System.out.println(users.size());
PageInfo<User> result = new PageInfo<>(users);
return result;
}
public int insert(User user){
return userDao.insert(user);
}
}
编写 UserController.java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{userId}")
public User getUser(@PathVariable String userId){
ByUserId(userId);
}
@GetMapping("/user")
public List<User> getAll(){
All();
}
@GetMapping("/user/page/{pageNum}")
public Object getPage(@PathVariable int pageNum,
@RequestParam(name = "pageSize",required = false,defaultValue = "10") int pageSize){ All(pageNum,pageSize);
}
@PostMapping("/user")
public Object addOne(User user){springboot结构
userService.insert(user);
return user;
}
}
启动项⽬,通过 postman 进⾏请求测试,测试结果如下:插⼊数据:
查询数据
分页查询
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论