Announcement Announcement Module
Collapse
No announcement yet.
No new records made after an Insert transaction. Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • No new records made after an Insert transaction.

    Hello developers,

    I am having a major problem with my project, I am using Spring 3 and jpa to make a web crud app. When i tried to insert a record to my Customer table no errors detected but when i checked my database there are no new records in my Customer table. Please help me with my problem.
    Here are my configurations that maybe bring caused to my problem:

    CustomerServiceImpl.java
    Code:
    @Repository("customerDAO")
    @Transactional
    public class CustomerServiceImpl implements CustomerService {
    
    	@PersistenceContext
    	private EntityManager em;
    
    	public void setEntityManager(EntityManager em) {
    		this.em = em;
    	}
    
    	public void save(Customer customer) {
    		em.persist(customer);
    
    	}
    
    	@SuppressWarnings("unchecked")
    	public List<Customer> findAll() {
    		Query query = this.em.createQuery("from Customer");
    		return query.getResultList();
    	}
    
    }
    root-context.xml
    Code:
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    		destroy-method="close">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
    		<property name="url" value="jdbc:mysql://localhost:3306/mydatabase" />
    		<property name="username" value="root" />
    		<property name="password" value="" />
    	</bean>
    
    	<context:annotation-config />
    	<tx:annotation-driven transaction-manager="transactionManager" />
    
    	<bean id="entityManagerFactory"
    		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="persistenceUnitName" value="customer" />
    		<property name="dataSource" ref="dataSource" />
    		<!-- <property name="jpaVendorAdapter"> -->
    		<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> -->
    		<!-- <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" 
    			/> -->
    		<!-- <property name="showSql" value="true" /> -->
    		<!-- <property name="generateDdl" value="true" /> -->
    		<!-- </bean> -->
    		<!-- </property> -->
    	</bean>
    
    	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="entityManagerFactory" />
    	</bean>
    
    	<bean id="customerDAO" class="com.rodel.SpringApp.CustomerServiceImpl" />
    
    	<bean
    		class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    persistence.xml
    Code:
    <persistence-unit name="customer">
    		<provider>org.hibernate.ejb.HibernatePersistence</provider>
    		<properties>
    			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
    			<!-- value="create" to build a new database on each run; value="update" 
    				to modify an existing database; value="create-drop" means the same as "create" 
    				but also drops tables when Hibernate closes; value="validate" makes no changes 
    				to the database -->
    			<property name="hibernate.hbm2ddl.auto" value="create" />
    			<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
    			<property name="hibernate.connection.charSet" value="UTF-8" />
    			<!-- Uncomment the following two properties for JBoss only -->
    			<!-- property name="hibernate.validator.apply_to_ddl" value="false" / -->
    			<!-- property name="hibernate.validator.autoregister_listeners" value="false" 
    				/ -->
    		</properties>
    	</persistence-unit>
    Any help please.
    Thanks.

  • #2
    In your persistence.xml
    <property name="hibernate.hbm2ddl.auto" value="create" />

    This creates a database for each run & then drops the tables after hibernate closes.

    Comment


    • #3
      ahh..ok. Thanks. So what's should be there? any help?
      Thanks.

      Comment


      • #4
        try using value="update"

        Comment


        • #5
          Thanks, but still no new records made. My table still has a 0 records inside. What i observe in my log is that I think it does not performing the insert. here is the log during my execution of the app:

          Code:
          Jun 8, 2011 1:46:09 PM org.apache.catalina.connector.CoyoteAdapter service
          SEVERE: An exception or error occurred in the container during the request processing
          java.lang.NullPointerException
          	at org.apache.catalina.connector.CoyoteAdapter.postParseRequest(CoyoteAdapter.java:638)
          	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:390)
          	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
          	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
          	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
          	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
          	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
          	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
          	at java.lang.Thread.run(Thread.java:637)
          Jun 8, 2011 1:46:09 PM org.apache.catalina.startup.Catalina start
          INFO: Server startup in 19376 ms
          INFO : com.rodel.SpringApp.HomeController - Welcome home!
          Hibernate: select customer0_.id as id0_, customer0_.firstname as firstname0_, customer0_.lastname as lastname0_ from customer customer0_
          Hibernate: select customer0_.id as id0_, customer0_.firstname as firstname0_, customer0_.lastname as lastname0_ from customer customer0_
          the first one is before im inserting new customer, and the second one is after the insert of new customer. Based on my log, it only performs select and no insert.
          What do you think is the problem here? any help please.
          Thanks.
          Last edited by presidentrodel; Jun 8th, 2011, 12:58 AM.

          Comment


          • #6
            Can you share the unit test case that you are executing.

            Comment


            • #7
              Well, actually i dont use unit test. I test it manually. Here are my codes :

              CustomerController
              Code:
              @Controller
              @RequestMapping(value = "/customer")
              public class CustomerTransactionController {
              
              	@Autowired
              	private CustomerServiceImpl customerDAO;
              
              	private final Logger logger = LoggerFactory
              			.getLogger(CustomerTransactionController.class);
              
              	@RequestMapping(method = RequestMethod.GET)
              	public String getCustomer(Model model) {
              		List<Customer> customers = customerDAO.findAll();
              		model.addAttribute("customers", customers);
              		return "customerHomePage";
              	}
              
              	@RequestMapping(value = "/addCustomer", method = RequestMethod.GET)
              	public String add(@ModelAttribute Customer customer) {
              		return "addCustomer";
              	}
              
              	@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
              	public String addSuccess(@ModelAttribute Customer customer) {
              		customerDAO.save(customer);
              		logger.info("redirecting to customer home page...");
              		return "redirect:/customer";
              	}
              }
              customerServiceImpl
              Code:
              @Repository("customerDAO")
              @Transactional
              public class CustomerServiceImpl implements CustomerService {
              
              	@PersistenceContext
              	private EntityManager em;
              	private final Logger logger = LoggerFactory
              			.getLogger(CustomerServiceImpl.class);
              
              	public void save(Customer customer) {
              		logger.info("Inserting new customer");
              		em.merge(customer);
              		logger.info("Inserting new customer finsihed");
              	}
              
              	@SuppressWarnings("unchecked")
              	public List<Customer> findAll() {
              		logger.info("searching all customers...");
              		Query query = this.em.createQuery("from Customer");
              		return query.getResultList();
              	}
              
              }
              customer
              Code:
              @Entity
              @Table(name = "Customer")
              public class Customer {
              
              	@Id
              	@GeneratedValue
              	private Long id;
              
              	@Column(name = "Firstname")
              	private String firstName;
              
              	@Column(name = "Lastname")
              	private String lastName;
              
              	public Long getId() {
              		return id;
              	}
              
              	public void setId(Long id) {
              		this.id = id;
              	}
              
              	public String getFirstName() {
              		return firstName;
              	}
              
              	public void setFirstName(String firstName) {
              		this.firstName = firstName;
              	}
              
              	public String getLastName() {
              		return lastName;
              	}
              
              	public void setLastName(String lastName) {
              		this.lastName = lastName;
              	}
              
              }
              and this is the log after the execution.
              Code:
              INFO : com.rodel.SpringApp.HomeController - Welcome home!
              INFO : com.rodel.SpringApp.CustomerServiceImpl - searching all customers...
              Hibernate: select customer0_.id as id0_, customer0_.firstname as firstname0_, customer0_.lastname as lastname0_ from customer customer0_
              INFO : com.rodel.SpringApp.CustomerServiceImpl - Inserting new customer
              INFO : com.rodel.SpringApp.CustomerServiceImpl - Inserting new customer finsihed
              INFO : com.rodel.SpringApp.CustomerTransactionController - redirecting to customer home page...
              INFO : com.rodel.SpringApp.CustomerServiceImpl - searching all customers...
              Hibernate: select customer0_.id as id0_, customer0_.firstname as firstname0_, customer0_.lastname as lastname0_ from customer customer0_
              hope it helps to solve the problem.
              thanks.
              Last edited by presidentrodel; Jun 8th, 2011, 02:32 AM.

              Comment


              • #8
                This is probably due to the fact that there is no transaction when the call to CustomerServiceImpl#save() is called.
                I believe this is since you do the call directly to the class CustomerServiceImpl and not via a dynamic proxy.

                Either try to change so that you use a CustomerService in CustomerTransactionController;

                Code:
                public class CustomerTransactionController {
                
                	@Autowired
                	private CustomerService customerDAO;
                Or you can use
                Code:
                	    <tx:annotation-driven proxy-target-class="true"/>
                to force Spring to use CGLIB.

                See 7.6 Proxying mechanisms
                Last edited by ullgren; Jun 9th, 2011, 05:38 PM. Reason: Added reference to documentation.

                Comment


                • #9
                  Wow. Thanks ullgren, it helps a lot. Everything is fine now.
                  Thanks.

                  Comment

                  Working...
                  X