springboot整合mybatis和jpa的使用
时间: 2023-11-09 22:12:10 浏览: 110
Spring Boot是一个基于Spring框架的快速开发脚手架,可以帮助开发者快速搭建一个Spring应用。MyBatis和JPA是两个流行的ORM框架,可以帮助开发者将Java对象映射到数据库表。
Spring Boot整合MyBatis的使用:
1. 添加MyBatis和MySQL的依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 配置数据源和MyBatis:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
# MyBatis Mapper文件的位置
mybatis:
mapper-locations: classpath:mapper/*.xml
# 实体类的包名
type-aliases-package: com.example.demo.model
```
3. 编写MyBatis Mapper:
```xml
<!-- UserMapper.xml -->
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getUserById" resultType="com.example.demo.model.User">
select * from user where id = #{id}
</select>
</mapper>
```
4. 编写UserMapper接口:
```java
@Mapper
public interface UserMapper {
User getUserById(int id);
}
```
5. 在需要使用的地方注入UserMapper:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
}
```
Spring Boot整合JPA的使用:
1. 添加JPA和MySQL的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 配置数据源和JPA:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
properties:
# 打印JPA的SQL语句
hibernate:
show_sql: true
format_sql: true
```
3. 编写实体类:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int age;
// 省略getter和setter
}
```
4. 编写JpaRepository:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
```
5. 在需要使用的地方注入UserRepository:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(int id) {
return userRepository.findById(id).orElse(null);
}
}
```
总结:
Spring Boot整合MyBatis和JPA的使用方法基本相似,只是依赖和配置略有不同。MyBatis需要编写Mapper和XML文件,JPA需要编写实体类和JpaRepository接口。使用时只需要在需要使用的地方注入Mapper或Repository即可。
阅读全文