使用Spring Boot和JPA时如何保持

Jan*_*ert 6 java spring jpa spring-data spring-boot

我习惯使用Spring Roo来生成我的实体,让它通过AspectJ类处理实体管理以及持久化和其他方法.现在我正在尝试使用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;
  }
Run Code Online (Sandbox Code Playgroud)

当我调用persist或merge时,entityManager显然是null.

我也尝试添加implements CrudRepository<Account, Long>Account类中,看它会通过默认实现给我这个功能,但我得到的只是需要填写的空类.

我已经看过Spring Boot文档了,他们非常简单地介绍了它,只是省略了足够的细节,以至于我不知道我错过了什么.

我有一个Application类来引导应用程序:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

  public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }

}
Run Code Online (Sandbox Code Playgroud)

我的属性文件如下所示:

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
Run Code Online (Sandbox Code Playgroud)

由于该ddl-auto=update属性,将自动创建此数据库

在Spring Boot + JPA中持久保存实体的正确方法是什么?如果到目前为止我所做的是正确的,我如何"自动装配"或自动创建entityManager?

fra*_*cis 8

在您的示例中,您EntityManager始终为null.Spring不会自动将一个连接到你的Entity班级.我也不确定你的目标是什么,但是我愿意打赌你很可能不希望你Entity拥有你的目标EntityManager

我认为您可能正在寻找的是Spring Data Repositories.我建议阅读它以获得基础知识.

要开始使用存储库:

我要做的第一件事就是删除你班上transient EntityManager entityManager;persist/merge功能Account.

Application课堂内,您可以添加@EnableJpaRepositories注释.

接下来创建一个新的Interface(不是新类),这将是您的Account存储库.

@Repository
public interface AccountRepository extends PagingAndSortingRepository<Account, Long>
Run Code Online (Sandbox Code Playgroud)

哪里Account是类型EntityLong是的ID类型Account

存在一些存储库接口,其中包含继承自Spring Data的各种支持Repository.

在不向界面添加任何内容的情况下,PagingAndSortingRepository将为您提供支持CRUD操作和分页.

它也可以使用JPQL向您的界面添加自定义查询,看一下@Query注释.http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

现在,您可以@Autowire AccountRepository进入任何Spring托管bean并开始保存和获取数据.

  • Roo基于Active Record模式,实体可以自行管理.Spring Data基于Repository模式,其中一个单独的对象负责管理域对象. (2认同)