Spring Data JPA事务问题

时间:2017-05-11 19:56:13

标签: hibernate spring-data

我的代码真的非常简化,如下所示:

@Entity
public class Item {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private int id;

    @Pattern(regexp="^[a-zA-Z0-9.\\s]+$", message="only letters, numbers, spaces and {.!}!")
    private String name;

    // getter, setter
}

我的Jpa存储库:

public interface ItemJpaRepository extends JpaRepository<Item, Integer>{}

我的服务:

@Service
@Transactional
public class ItemService {

    @Autowired
    ItemDAO itemDAO;

    @Autowired
    ItemJpaRepository itemJpaRepository;

    public void saveOrUpdateItem(){
        itemDAO.saveOrUpdateItem(); //working
        itemJpaRepository.save(entity) //not working
    }

    public void findAllItems(){
        System.out.println(itemJpaRepository.findAll());
    }
}

用于数据库连接的Bean声明如下:

@Bean
public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/shoppingcartspringmvcspringdatahibernate");
    dataSource.setUsername("root");
    dataSource.setPassword("Scholl1313.");
    //dataSource.setValidationQuery("select 1");

    return dataSource;
}

@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory() {

    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(getDataSource());
    sessionBuilder.scanPackages("com.zdranganele.models");
    sessionBuilder.setProperty("hibernate.show_sql", "true");
    sessionBuilder.setProperty("hibernate.hbm2ddl.auto", "create");
    sessionBuilder.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    return sessionBuilder.buildSessionFactory();
}

@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager() {

    HibernateTransactionManager transactionManager = new HibernateTransactionManager(getSessionFactory());
    return transactionManager;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(getDataSource());
    entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
    entityManagerFactoryBean.setPackagesToScan("com.zdranganele.models");

    return entityManagerFactoryBean;
}

ItemDao是经典的DAO。按ItemDao保存,ItemJpaRepository保存不会。也用于删除。仅查找ItemJpaRepository上的作品。没有错误被抛出,所以我猜这是交易永远不会被提交的东西。

0 个答案:

没有答案