springboot整合jpa和mybatis
时间: 2023-04-28 22:03:06 浏览: 103
Spring Boot可以很方便地整合JPA和MyBatis。
整合JPA:
1. 在pom.xml中添加JPA依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
2. 配置数据源和JPA属性:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
```
3. 创建实体类和Repository接口:
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// getter和setter
}
public interface UserRepository extends JpaRepository<User, Long> {
}
```
4. 在Service中使用Repository:
```
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public void saveUser(User user) {
userRepository.save(user);
}
public void deleteUserById(Long id) {
userRepository.deleteById(id);
}
}
```
整合MyBatis:
1. 在pom.xml中添加MyBatis依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.</version>
</dependency>
```
2. 配置数据源和MyBatis属性:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
3. 创建实体类和Mapper接口:
```
public class User {
private Long id;
private String name;
private Integer age;
// getter和setter
}
@Mapper
public interface UserMapper {
User getUserById(Long id);
void saveUser(User user);
void deleteUserById(Long id);
}
```
4. 在Service中使用Mapper:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
public void saveUser(User user) {
userMapper.saveUser(user);
}
public void deleteUserById(Long id) {
userMapper.deleteUserById(id);
}
}
```