Springboot + mybatis + postgreSQL
为了提供一个完整的解决方案,我们需要具体的问题或者需求。由于你没有提供具体的问题,我将提供一个简单的Spring Boot + MyBatis + PostgreSQL的示例,包括创建一个简单的用户表,并提供基本的CRUD操作。
- 首先,在
pom.xml
中添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 在
application.properties
中配置数据库连接:
spring.datasource.url=jdbc:postgresql://localhost:5432/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=org.postgresql.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
- 创建一个用户实体类
User.java
:
public class User {
private Integer id;
private String name;
// getters and setters
}
- 创建一个MyBatis映射器接口
UserMapper.java
:
@Mapper
public interface UserMapper {
int insertUser(User user);
User getUserById(int id);
// 更多的CRUD操作
}
- 创建MyBatis映射文件
UserMapper.xml
:
<mapper namespace="com.example.mapper.UserMapper">
<insert id="insertUser" parameterType="User">
INSERT INTO users (name) VALUES (#{name})
</insert>
<select id="getUserById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
<!-- 更多的CRUD操作 -->
</mapper>
- 创建一个服务类
UserService.java
:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int createUser(User user) {
return userMapper.insertUser(user);
}
public User getUserById(int id) {
return userMapper.getUserById(id);
}
// 更多的CRUD操作
}
- 创建一个控制器类
UserController.java
:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
userService.createUser(user);
return new ResponseEntity<>(user, HttpStatus.CREATED);
评论已关闭