不工作entitymanager.persist / merge

时间:2016-04-07 20:05:40

标签: java spring hibernate

Spring MVC / Security,hibernate项目。结构:

enter image description here

当我使用来自控制器的方法,其中包含查询 - 所有工作正常, 但不能使用持久/合并。

控制台显示仅选择查询 enter image description here

无法正常工作 - 将产品添加到数据库

 @Override
    public  void addProduct(Products product){
        entityManager.persist(product);
    }

正常工作 - 在视图中显示产品。

 @Override
    public List<Products> listall(){
        Query query;
        query = entityManager.createQuery("select p From Products p");
        return( List<Products>) query.getResultList();

春季配置

@EnableWebMvc
@Configuration
@ComponentScan({"com.vdp.*"})
@EnableTransactionManagement
@Import({ SecurityConfig.class })
    public class AppConfig {

        @Bean(name = "dataSource")
        public BasicDataSource dataSource() {

            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setUrl("jdbc:mysql://localhost:3306/proj");
            ds.setUsername("root");
            ds.setPassword("root");
            return ds;
        }


        @Bean
        public SessionFactory sessionFactory() {
            LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
            builder
                .scanPackages("com.vdp.users")
                .addProperties(getHibernateProperties());
                 return builder.buildSessionFactory();
        }


        private Properties getHibernateProperties() {
            Properties prop = new Properties();
            prop.put("hibernate.format_sql", "true");
            prop.put("hibernate.show_sql", "true");
            prop.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            return prop;
        }


        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory
                (DataSource dataSource, JpaVendorAdapter jpaVendeorAdapter)
        {
            LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
            entityManagerFactory.setDataSource(dataSource);
            entityManagerFactory.setJpaVendorAdapter(jpaVendeorAdapter);
            entityManagerFactory.setPackagesToScan("com.vdp*");
            return entityManagerFactory;
        }

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




    @Bean
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }

    @Bean
    public HibernateTransactionManager txManager() {
        return new HibernateTransactionManager(sessionFactory());
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

实体

@Table(name = "products")
public class Products implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idProducts")
    private long id;

    @Column(name = "description")
    private String description;

    @Column(name = "price")
    private String price;

    @Column(name = "image")
    private byte [] image;

    public Products() {
    }

    public Products(String description, String price, byte[] image) {
        this.description = description;
        this.price = price;
        this.image = image;
    }

    public Products(String description, String price, byte[] image, List<Category> categories) {
        this.description = description;
        this.price = price;
        this.image = image;
        this.categories = categories;
    }



    @ManyToMany
    @JoinTable(
       name = "category_products",
            joinColumns ={@JoinColumn (name = "Products_idProducts", referencedColumnName = "idProducts")},
            inverseJoinColumns = {@JoinColumn(name = "category_id", referencedColumnName = "id")}
    )
        List<Category> categories = new ArrayList<Category>();


    @ManyToMany
    @JoinTable(
            name = "users_product",
            joinColumns ={@JoinColumn (name = "Products_idProducts", referencedColumnName = "idProducts")},
            inverseJoinColumns = {@JoinColumn(name = "users_username", referencedColumnName = "username")}
    )
      List<User> usersList = new ArrayList<User>();

交易部分:

 @Service
    public class MyService {

        @Autowired
        private UserDao userDao;

        @Autowired
        private CategoryDAO categoryDAO;

        @Autowired
        private ProductsDAO productsDAO;

        //admin part---------------------------------------
        @Transactional
        public void deleteOneProduct(Products product){
            productsDAO.deleteOne(product);
        }

        @Transactional
        public void deleteManyProducts(long [] toDelete){
            productsDAO.deleteMany(toDelete);
        }

//not working!!!!
          @Transactional 
        public void addProduct(Products product){
            productsDAO.addProduct(product);
        }

        @Transactional
        public  List <Products> displayProducts(){
          return   productsDAO.listall();
        }



     // end of admin part---------------------------------------

1 个答案:

答案 0 :(得分:0)

我找到了原因 - 需要从AppConfig中删除bean&#39; s - 1,2和5,然后添加:

@Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
        return new JpaTransactionManager(emf);
    }