在springbootdata数据库中创建表user,包括字段id name pass,并输入数据。用Mybatis按i d查询,将查询结果输出到控制台
时间: 2024-10-12 15:18:03 浏览: 21
在Spring Boot Data JPA中,首先需要设置数据库连接配置并添加JPA和MyBatis的支持。假设我们已经在pom.xml文件中配置了相关依赖。以下是创建User实体类(User.java)、配置数据库表(user)以及插入数据的步骤:
1. **创建User实体类**(User.java):
```java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String password;
// getter和setter方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
2. **配置实体扫描和数据源** (application.properties):
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
mybatis.mapper-locations=classpath:mapper/*.xml
```
3. **创建MyBatis映射文件** (mapper/UserMapper.xml):
```xml
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="findById" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
```
4. **编写Service层** (UserService.java):
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.UserMapper;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.findById(id);
}
}
```
5. **在Controller中调用并打印结果** (UserController.java):
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long id) {
User user = userService.getUserById(id);
System.out.println("User details: " + user);
return user;
}
}
```
现在你可以通过HTTP请求`http://localhost:8080/users/{id}`来获取指定ID的用户信息,其中{id}会被实际的用户ID替换。
阅读全文