我已经失去了耐心。我是第一次尝试打开JPA而且我仍然得到Null Pointer Exception ...我不知道下一步该做什么。请帮忙。 我试着像书中一样#34; Spring in action"。
@Configuration
@EnableJpaRepositories(basePackages = {"org.project"})
public class JpaConfig {
private DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("org.project.persistance");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
存储库:
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
@Repository
public class DogRepositoryImpl implements DogRepository {
@PersistenceUnit
private EntityManagerFactory entityManager;
@Override
public Dog findById(long id) {
return entityManager.createEntityManager().find(Dog.class, id);
}
@Override
public void persist(Dog dog) {
entityManager.createEntityManager().persist(dog);
}
}
和@Entity:
@Entity
@Table(name = "dogs")
public class Dog {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String owner;
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 getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
请帮助:( 当我尝试使用Spring Data时,它是一样的。
PS:**为什么在MySql中的控制器表中执行此代码后,清理' ? **
答案 0 :(得分:0)
这应该是由这一行引起的:
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
会话工厂关闭后,所有表都将被删除。您可以将其更改为create
,以便表格保持不变。