Spring multiple transaction roll back - mysql

I have a requirement wherein I have to insert into 3 separate tables through 3 DAO classes.
ClassADAO
ClassBDAO
ClassCDAO
I want to have a single transaction for all the three classes so that if one insertion fails I want to roll back the complete transaction that is inserted through previous classes.
I have my configured xml as shown below
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"></property>
<property name="username" value="******"></property>
<property name="password" value="********"></property>
</bean>
In controller annotated as follows
#Transactional(rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
But still if ClassCDAO fails, I can c insertions in my db from ClassA and ClassB
Controller:
#Controller
#Transactional(rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
public class MyController{
#Autowired
private MyBusinessLayer mybusinessLayer;
#RequestMapping(value = "/register.htm", method = RequestMethod.POST)
public String saveRegistration(
final #ModelAttribute("registration") #Valid Registration registration,
final BindingResult result, final Model model) {
if (result.hasErrors()) {
return "myPage";
} else {
mybusinessLayer.saveRegistration(registration);
}
return "myPage";
}
}
My Business Layer:
#Component
public class MyBusinessLayer{
#Autowired
private ClassA classA;
#Autowired
private ClassB classB;
#Autowired
private ClassC classC;
public void saveRegistration(Registration registration) {
Company company = RegistrationHelper.buildCompany(registration);
classA.saveCompany(company);
Contact contact = RegistrationHelper.buildContact(registration, company.getCompanyId());
classB.saveContact(contact);
User user = RegistrationHelper.buildUser(registration, contact.getCompanyID(),
contact.getContactID());
classC.saveUser(user);
}
}
ClassADAO:
#Component
public class CompanyDAOImpl implements CompanyDAO {
#Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
#Override
public void saveCompany(Company company) {
String insertCompanySQL = //insert statement;
//code here
SqlParameterSource paramSource = new MapSqlParameterSource(bind);
namedParameterJdbcTemplate.update(insertCompanySQL, paramSource);
}
}
ClassBDAO and ClassCDAO are also as shown above.

Move your #Transactional annotation to MyBusinessLayer class. Unless you have your DataSource configured as autocommit, your code seems correct.

Related

Hibernate #OneToOne gets a NullPointer Exception

I am reviewing my Java skills and your support to the community is amazing, your tips have helped me a lot.
I am stuck in a Hibernate #OneToOne configuration, it is a very simple design and code but I can´t find the error. I´d really appreciate your help.
This is the user.java code, the user_id is generated by an autoincrement column at MySQL. I have omitted hash() and equals() code for simplicity. Hibernate understands the User class but something is missing to get to the Address class that is at the other side of the relationship.
Any help would be very appreciated.
Thank you
1) This is the user.java:
package myPackage;
import java.io.Serializable;
import java.util.Arrays;
import javax.persistence.*;
#Entity
#Table(name="user1")
public class User implements Serializable {
private static final long serialVersionUID = 3271213543123246487L;
#Id
#GeneratedValue
#Column(name="user_id")
private Integer user_id;
#Column(name="user_name", length=100, nullable=false)
private String user_name;
#OneToOne (cascade= CascadeType.ALL)
#PrimaryKeyJoinColumn(name="user_id")
private Address myAddress;
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public Address getMyAddress() {
return myAddress;
}
public void setMyAddress(Address myAddress) {
this.myAddress = myAddress;
}
}
2) This is the Address.java code:
package myPackage;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="address1")
public class Address implements Serializable {
private static final long serialVersionUID = 3605176021936036836L;
#Id
#GeneratedValue(generator="address_ibfk_2")
#org.hibernate.annotations.GenericGenerator(name="address_ibfk_2",
strategy="foreign",parameters =#Parameter(name="property",value="user1"))
#Column(name="user_id")
private Integer user_id;
#Column(name="address_line1", length=100, nullable=false)
private String address_line1;
public String getAddress_line1() {
return address_line1;
}
public void setAddress_line1(String address_line1) {
this.address_line1 = address_line1;
}
}
3) This is the very simple TestUser class
public class TestUser {
public static void main(String[] args) {
Session mySession = HibernateUtil.getSessionFactory().openSession();
System.out.println("Connection status"+mySession.isConnected());
System.out.println("Session status"+mySession.isOpen());
Transaction myTransaction = mySession.beginTransaction();
try {
User myUser = new User();
Address myAddress = new Address();
myUser.setUser_name("TesteO2O");
myAddress.setAddress_line1("Rua A");
myUser.setMyAddress(myAddress);
mySession.save(myUser);
myTransaction.commit();
System.out.println("myUser saved sucessfully");
} catch (Exception e) {
e.printStackTrace();
myTransaction.rollback();
} finally {
mySession.close();
}
}
}
4) This is the hibernate.cfg.xml config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--MySQL Config-->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/p2pl_dev?serverTimezone=UTC</property>
<property name="connection.username">xyz</property>
<property name="connection.password">blabla</property>
<property name="current_session_context_class">thread</property>
<!--Connection Pool Config: max_statements cached, idle time in seconds-->
<property name="c3po.min_size">2</property>
<property name="c3po.max_size">3</property>
<property name="c3po.timeout">300</property>
<property name="c3po.max_stamentes">50</property>
<property name="c3po.idle_test_period">3000</property>
<!--Debug Config, show_sql=console, format_sql=legible -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="generate_statistics">true</property>
<property name="use_sql_comments">true</property>
<!-- Classes -->
<mapping class="myPackage.User"/>
<mapping class="myPackage.Address"/>
</session-factory>
</hibernate-configuration>
5) Finally the error trace
Hibernate:
/* insert myPackage.User
*/ insert
into
user1
(user_name)
values
(?)
java.lang.NullPointerException
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:650)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4736)
at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:96)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.engine.spi.CascadingActions$5.cascade(CascadingActions.java:235)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:460)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:294)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at myPackage.TestUser.main(TestUser.java:26)

HTTP Status 500 - Servlet.init() for servlet management threw exception

Emp.java
package com.management;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.management;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.management.Emp;
import com.management.EmpDao;
#Controller
public class EmpController {
#Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
#RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The #ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
#RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
/* It displays object data into form for the given id.
* The #PathVariable puts URL data into variable.*/
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable int id){
Emp emp=dao.getEmpById(id);
return new ModelAndView("empeditform","command",emp);
}
/* It updates model object. */
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp") Emp emp){
dao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
/* It deletes record for the given id in URL and redirects to /viewemp */
#RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int id){
dao.delete(id);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.management;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.management.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+", designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
servlet-management.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.spring" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.spring.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>management</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>management</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hi
my trying to insert the value to the database by using the spring-mvc.
and using the mysql database.
while execution process it shows the error like that-org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.spring.EmpDao] for bean with name 'dao' defined in ServletContext resource [/WEB-INF/management-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.spring.EmpDao .
please provide the soluation.
thank you.

Hibernate cannot create table when the entity annotation?

My web project ,spring spring-mvc and hibernate,when the tomcat start there is no tables created in mysql db. why? and no error info
the sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.woodcoder.bean</value>
</list>
</property>
</bean>
the properties
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
and I tried hibernate.hbm2ddl.auto=create, it's the same.
Why hibernate doesn't create a table?
The Entity
#Entity
#Table(name="user_bean")
public class UserBean extends BaseBean {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
the baseEntity
#MappedSuperclass
public class BaseBean implements Serializable{
/**
* ID
*/
#Id
#Column(name="id",length = 32, nullable = true)
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
private String id;
#Column(updatable = false)
private Date createDate;
private Date modifyDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
yes,i got the problem.
in the hibernate config there are some space in the end of each line,although i cant see them.i delete these space,the table was created.
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false

json request not parsed in controller correctly

i am struggling with something that should work but doesn't...
i have this mapping in my controller:
#RequestMapping(value = "/keys", method = RequestMethod.POST)
#Consumes(MediaType.APPLICATION_JSON)
public ResponseEntity<Void> parseKeyList(keyList keyList) {
return new ResponseEntity<Void>(HttpStatus.OK);
}
with the simple class
#XmlRootElement
public class keyList {
private String keys;
public String getKeys() {
return keys;
}
public void setKeys(String keys) {
this.keys = keys;
}
}
And I am sending this simple JSON post:
{"keys": "This is my key list"}
but I am getting null in the keys.
As requested the original dispatcher-servlet:
<context:component-scan base-package="com.api" />
<!-- <mvc:resources mapping="/*" location="/WEB-INF/pages/" /> -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
You haven't attached your keyList param to the request body, change the method to:
#RequestMapping(value = "/keys", method = RequestMethod.POST)
#Consumes(MediaType.APPLICATION_JSON)
public ResponseEntity<Void> parseKeyList(#RequestBody keyList keyList) {
return new ResponseEntity<Void>(HttpStatus.OK);
}
Btw.: Class keyList should rather be KeyList (with big K).
Also there is (look at the chat) a
<mvc:annotation-driven/>
missing from your dispatcher-servlet.xml. That's the one that is registering the jackson mapper/marshaller.

Flex 4, Spring 3 BlazeDS4 mySQL dbcp query excecution

I've implemented the SpringFlex 1.5 with a connection to mySQL DB
and it works and retrieves data initially but when I enter an invalid
data that doesn't exist in my table the application seems to freeze
and not even entering valid data works after that and I need to
stop and start Tomcat again to get it working again
applicationContext.xml
<bean id="authToLeaveService" class="com.model.atl.AuthToLeaveServiceImpl">
<constructor-arg ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://dxfcm:3306/wookie?autoReconnect=true&zeroDateTimeBehavior=convertToNull"/>
<property name="username" value="darth" />
<property name="password" value="vader" />
<property name="validationQuery" value="SELECT 1"/>
</bean>
MyView
<fx:Declarations>
<s:ChannelSet id="cs">
<s:AMFChannel url="http://localhost:8400/flexspring/messagebroker/amf"/>
</s:ChannelSet>
<s:RemoteObject id="atlRO" channelSet="{cs}" destination="authToLeaveService"/>
</fx:Declarations>
[Bindable]
private var job:AtlJob;
private function onEnter(event:FlexEvent):void
{
var token:AsyncToken = atlRO.findByBarcode(this.txtBarcode.text);
token.addResponder(new AsyncResponder(onResult, onFault));
}
private function onResult(event:ResultEvent, token:Object):void
{ job = event.result as AtlJob; }
private function onFault(event:FaultEvent, token:Object):void
{ }
<s:TextInput id="txtBarcode" x="23" y="60" width="218"
enter="onEnter(event)" maxChars="16"/>
AltJob.as
[Bindable]
[RemoteClass (alias="com.model.atl.AtlJob")]
public class AtlJob
{
public var barcode:String;
public var pieces:int;
public var customerName:String;
}
AtlJob.java
package com.model.atl;
public class AtlJob implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String barcode;
private String customerName;
private int pieces;
public AtlJob() { }
public AtlJob(String barcode, int pieces, String customerName) {
this.barcode = barcode;
this.customerName = customerName;
this.pieces= pieces;
}
Getters and Setters defined
#Service("authToLeaveService")
#RemotingDestination(channels = { "my-amf", "my-secure-amf" })
public class AuthToLeaveServiceImpl implements AuthToLeaveService {
private final DataSource dataSource;
public AuthToLeaveServiceImpl(DataSource dataSource) {
this.dataSource = dataSource; }
#RemotingInclude
public AtlJob findByBarcode(String barcode) {
AtlJob job = new AtlJob();
Connection con = null;
final String sql = "SELECT * FROM atl_job WHERE card_barcode = ?";
try {
con = this.dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, barcode);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
job.setBarcode(rs.getString("barcode"));
job.setPieces(rs.getInt("pieces"));
job.setCustomerName(rs.getString("customerName"));}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (con!=null) {try { con.close();
} catch (SQLException e) {
e.printStackTrace();
} }} return job; }
You are not throwing any exceptions if the record is not found like here
...
if (rs.next()) {
job.setBarcode(rs.getString("barcode"));
job.setPieces(rs.getInt("pieces"));
job.setCustomerName(rs.getString("customerName"));
}
// Put an else clause here and throw exception
else
{
throw new Exception("Record Not found");
}
Try showing caught exception in your faultMethod ..
private function onFault(event:FaultEvent, token:Object):void
{
//Handle Fault event here Put some Alert here
}