// 实体类定义,使用 JPA 注解来映射到数据库表
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 构造函数、getter 和 setter 方法
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
// 用户仓库接口,继承自 JPARepository 接口
public interface UserRepository extends JpaRepository<User, Long> {
// 可以添加自定义查询方法,例如按邮箱查找用户
User findByEmail(String email);
}
// 使用示例代码
@SpringBootApplication
public class Application {
@Autowired
private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
public void init() {
// 保存一个新用户
User user = new User("John Doe", "john.doe@example.com");
userRepository.save(user);
// 查找用户
User foundUser = userRepository.findByEmail("john.doe@example.com");
System.out.println("Found user: " + foundUser.getName());
}
}
实体类 (User
):
@Entity
注解将类映射到数据库表。@Id
和 @GeneratedValue
注解用于标识主键并自动生成其值。仓库接口 (UserRepository
):
JpaRepository
,提供了对数据库的基本 CRUD 操作。findByEmail
。应用启动类 (Application
):
@SpringBootApplication
注解来启动 Spring Boot 应用程序。@Autowired
注入 UserRepository
。init
方法中演示了如何保存和查找用户。上一篇:java分割string
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站