【发布时间】:2023-03-18 13:38:01
【问题描述】:
我习惯于使用 Spring Roo 来生成我的实体并让它通过 AspectJ 类处理注入 entityManager 以及 persist 和其他方法。 现在我正在尝试使用 Spring Boot 做一些简单的事情,将内容写入数据库......
@Entity
@Table(name = "account")
public class Account {
transient EntityManager entityManager;
@Id
@GeneratedValue
private Long id;
@Column(name = "username", nullable = false, unique = true)
private String username;
@Column(name = "password", nullable = false)
private String password;
... getters and setters
@Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public Account merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Account merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
当我调用persist 或merge 时,entityManager 显然为null。
我还尝试将implements CrudRepository<Account, Long> 添加到Account 类中,以查看它会通过默认实现为我提供该功能,但我得到的只是需要填写的空类。
我查看了 Spring Boot 文档,他们非常简要地介绍了它,省略了足够的细节,因此我遗漏了什么并不明显。
我有一个引导应用程序的应用程序类:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
我的属性文件如下所示:
spring.application.name: Test Application
spring.datasource.url: jdbc:mysql://localhost/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
由于ddl-auto=update 属性,此数据库会自动创建
在 Spring Boot + JPA 中持久化实体的正确方法是什么?如果到目前为止我所做的是正确的,我该如何“自动装配”或自动创建 entityManager?
【问题讨论】:
标签: java spring jpa spring-boot spring-data