EntityManager不会将对象合并到数据库

时间:2016-03-19 22:50:08

标签: java spring jpa

我有一个java spring应用程序并使用JPA

JPA初始化代码

@Configuration
@EnableJpaRepositories
public class Application {

@Bean
public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/database");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUsername("root");
    dataSource.setPassword("pass");
    dataSource.setInitialSize(20);
    dataSource.setMaxActive(30);
    return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    lef.setDataSource(dataSource);
    lef.setJpaVendorAdapter(jpaVendorAdapter);
    lef.setPackagesToScan("repository");
    return lef;
}

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setShowSql(false);
    hibernateJpaVendorAdapter.setGenerateDdl(true);
    hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
    return hibernateJpaVendorAdapter;
}

}

我也有简单的实体对象

@Entity
public class Client {
@Id
private int id;
private String name;
private String email;
private String phone;

public Client(){};

public Client(int id, String name, String email, String phone){
   this.id=id;
    this.name=name;
    this.email=email;
    this.phone=phone;
}

public int getId() {
    return id;
}

public void setId(int 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;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

}

和存储库

@Repository
public class ProductRepository {

@PersistenceContext
EntityManager em;

@Transactional
public void saveClient() {
Client cl = new Client(1,"Alex","alex@gmail.com","1111111111");
em.merge(cl);

    }
}

当我直接从控制器调用此方法时,我不会将数据合并到数据库

@Controller
@ComponentScan("repository")
@RequestMapping("/")
public class HomeController {

@Autowired
ProductRepository productRepository;

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
productRepository.saveClient();  
return "home";
    }
}

我没有得到任何编译或运行时异常和错误,但合并不会导致我的对象被保存

1 个答案:

答案 0 :(得分:0)

试试这个

@Configuration
@EnableTransactionManagement
public class Application {}

而不是

@Configuration
@EnableJpaRepositories
public class Application {}