Java SpringMVC和hibernate应该按需保存事务

Java SpringMVC和hibernate应该按需保存事务,java,hibernate,spring-mvc,autocommit,Java,Hibernate,Spring Mvc,Autocommit,我正在使用SpringMVC和hibernate。下面是我的代码示例 applicationContext.xml <context:annotation-config /> <context:component-scan base-package="com.soft.erp" /> <mvc:annotation-driven /> <import resource="hibernate-context.xml" /> <propert

我正在使用SpringMVC和hibernate。下面是我的代码示例

applicationContext.xml

<context:annotation-config />
<context:component-scan base-package="com.soft.erp" />
<mvc:annotation-driven /> 
<import resource="hibernate-context.xml" />
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
    <context:property-placeholder location="/WEB-INF/config.properties" />
<tx:annotation-driven transaction-manager="transactionManager" />   
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
             p:dataSource-ref="dataSource"
             p:configLocation="${hibernate.config}"
             p:packagesToScan="com.soft.erp"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
            destroy-method="close"
            p:driverClass="${app.jdbc.driverClassName}"
            p:jdbcUrl="${app.jdbc.url}"
            p:user="${app.jdbc.username}"
            p:password="${app.jdbc.password}"

            p:acquireIncrement="5"
            p:idleConnectionTestPeriod="60"
            p:maxPoolSize="100"
            p:maxStatements="50"
            p:minPoolSize="10" />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
            p:sessionFactory-ref="sessionFactory" />
hibernate.cfg.xml

<context:annotation-config />
<context:component-scan base-package="com.soft.erp" />
<mvc:annotation-driven /> 
<import resource="hibernate-context.xml" />
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
    <context:property-placeholder location="/WEB-INF/config.properties" />
<tx:annotation-driven transaction-manager="transactionManager" />   
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
             p:dataSource-ref="dataSource"
             p:configLocation="${hibernate.config}"
             p:packagesToScan="com.soft.erp"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
            destroy-method="close"
            p:driverClass="${app.jdbc.driverClassName}"
            p:jdbcUrl="${app.jdbc.url}"
            p:user="${app.jdbc.username}"
            p:password="${app.jdbc.password}"

            p:acquireIncrement="5"
            p:idleConnectionTestPeriod="60"
            p:maxPoolSize="100"
            p:maxStatements="50"
            p:minPoolSize="10" />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
            p:sessionFactory-ref="sessionFactory" />
CoCategoriesService.java

@Service("COACategoriesService")
@Transactional 
public class COACategoriesService {


@Resource(name="sessionFactory")
private SessionFactory sessionFactory;


public void AddCOACategories(COACategoriesModel accountCategories) {

Session session = sessionFactory.getCurrentSession();
session.save(accountCategories);

}
}

COAMaintenanceService.java

@Entity
@Table(name = "COACATEGORIES")
public class COACategoriesModel {

@Id
@Column(name = "COACATEGORIESID")
@GeneratedValue
private Long id;


public COACategoriesModel() {
    super();
}

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

@Column(name = "RECENTUSERID")
private long recentUserId;

@Column(name = "RECENTUSERIP")
private String recentUserIp;

@Column(name = "DATE")
private Date dateTime;

@Column(name = "ISUPDATED")
private int isUpdated;

@OneToMany(mappedBy="categoryId")
private List<COAMaintenanceModel> obj = null;


public COACategoriesModel( String name, long recentUserId,
        String recentUserIp, Date dateTime, int isUpdated) {

    this.name = name;
    this.recentUserId = recentUserId;
    this.recentUserIp = recentUserIp;
    this.dateTime = dateTime;
    this.isUpdated = isUpdated;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getRecentUserId() {
    return recentUserId;
}

public void setRecentUserId(Long recentUserId) {
    this.recentUserId = recentUserId;
}

public String getRecentUserIp() {
    return recentUserIp;
}

public void setRecentUserIp(String recentUserIp) {
    this.recentUserIp = recentUserIp;
}

public Date getDateTime() {
    return dateTime;
}

public void setDateTime(Date dateTime) {
    this.dateTime = dateTime;
}

public int getIsUpdated() {
    return isUpdated;
}

public void setIsUpdated(int isUpdated) {
    this.isUpdated = isUpdated;
}

public void setRecentUserId(long recentUserId) {
    this.recentUserId = recentUserId;
}

public List<COAMaintenanceModel> getObj() {
    return obj;
}

public void setObj(List<COAMaintenanceModel> obj) {
    this.obj = obj;
}
@Entity
@Table(name = "ACCOUNTMAINTENANCE")
public class COAMaintenanceModel {

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

@Column(name = "ACCOUNT")
private String account;

@Column(name = "DESCRIPTION")
private String discription;

@ManyToOne
@JoinColumn(name="COACATEGORIESID")
private COACategoriesModel categoryId;

@Column(name = "POSTINGTYPE")
private int postingType;

@Column(name = "TYPICALBALANCE")
private int typicalBalance;

@Column(name = "DEBITBALANCE")
private double debitBalance;

@Column(name = "CREDITBALANCE")
private double creditBalance;

@Column(name = "NETBALANCE")
private double runningBalance;

@Column(name = "DEFAULTCURRENCYID")
private double defaultCurrencyId;

@Column(name = "ISACTIVE")
private int isActive;

@Column(name = "RECENTUSERID")
private Long recentUserId;

@Column(name = "RECENTUSERIP")
private String recentUserIp;

@Column(name = "DATETIME")
private Date dateTime;

@Column(name = "ISUPDATED")
private int isUpdated;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getAccount() {
    return account;
}

public void setAccount(String account) {
    this.account = account;
}

public String getDiscription() {
    return discription;
}

public void setDiscription(String discription) {
    this.discription = discription;
}

public COACategoriesModel getCategoryId() {
    return categoryId;
}

public void setCategoryId(COACategoriesModel categoryId) {
    this.categoryId = categoryId;
}

public int getPostingType() {
    return postingType;
}

public void setPostingType(int postingType) {
    this.postingType = postingType;
}

public int getTypicalBalance() {
    return typicalBalance;
}

public void setTypicalBalance(int typicalBalance) {
    this.typicalBalance = typicalBalance;
}

public double getDebitBalance() {
    return debitBalance;
}

public void setDebitBalance(double debitBalance) {
    this.debitBalance = debitBalance;
}

public double getCreditBalance() {
    return creditBalance;
}

public void setCreditBalance(double creditBalance) {
    this.creditBalance = creditBalance;
}

public double getRunningBalance() {
    return runningBalance;
}

public void setRunningBalance(double runningBalance) {
    this.runningBalance = runningBalance;
}

public double getDefaultCurrencyId() {
    return defaultCurrencyId;
}

public void setDefaultCurrencyId(double defaultCurrencyId) {
    this.defaultCurrencyId = defaultCurrencyId;
}

public int getIsActive() {
    return isActive;
}

public void setIsActive(int isActive) {
    this.isActive = isActive;
}

public Long getRecentUserId() {
    return recentUserId;
}

public void setRecentUserId(Long recentUserId) {
    this.recentUserId = recentUserId;
}

public String getRecentUserIp() {
    return recentUserIp;
}

public void setRecentUserIp(String recentUserIp) {
    this.recentUserIp = recentUserIp;
}

public Date getDateTime() {
    return dateTime;
}

public void setDateTime(Date dateTime) {
    this.dateTime = dateTime;
}

public int getIsUpdated() {
    return isUpdated;
}

public void setIsUpdated(int isUpdated) {
    this.isUpdated = isUpdated;
}
@Service("COAMaintenanceService")
@Transactional
public class COAMaintenanceService {


@Resource(name="sessionFactory")
private SessionFactory sessionFactory;



public void AddCOAMaintenance(COAMaintenanceModel cMaintenanceModel) {

Session session = sessionFactory.getCurrentSession();
session.save(cMaintenanceModel);

}
@Controller
public class COACategoriesController {

protected static Logger log = Logger.getLogger(COACategoriesController.class);


@Resource(name="COACategoriesService")
private COACategoriesService obj_coacs;
@Resource(name="COAMaintenanceService")
private COAMaintenanceService obj_coams;

 @RequestMapping(value = "/addCoaCategory", method = RequestMethod.POST)
 public String addCoaCategory(@RequestParam("conCatName") String coaCatName, Model model) {

     Date sysdate = null;
     String Message="";
     try{

     sysdate = new Date();

     COACategoriesModel model1 = new COACategoriesModel( coaCatName, 1, "", sysdate , 0);

     COAMaintenanceModel account =  new COAMaintenanceModel();
        account.setDiscription("Test Description");
        account.setCategoryId(model1);

        Message="Fail-First";
        obj_coacs.AddCOACategories(model1);


        Message="Fail-Second";
        obj_coams.AddCOAMaintenance (account);


        Message="Successfully Added!";
     }catch(Exception ex){
         log.error("Exception.."+ex);
         model.addAttribute("message", Message);
     }


        return "fin/category";
    }



 }
}

COACategoriesController.java

@Entity
@Table(name = "COACATEGORIES")
public class COACategoriesModel {

@Id
@Column(name = "COACATEGORIESID")
@GeneratedValue
private Long id;


public COACategoriesModel() {
    super();
}

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

@Column(name = "RECENTUSERID")
private long recentUserId;

@Column(name = "RECENTUSERIP")
private String recentUserIp;

@Column(name = "DATE")
private Date dateTime;

@Column(name = "ISUPDATED")
private int isUpdated;

@OneToMany(mappedBy="categoryId")
private List<COAMaintenanceModel> obj = null;


public COACategoriesModel( String name, long recentUserId,
        String recentUserIp, Date dateTime, int isUpdated) {

    this.name = name;
    this.recentUserId = recentUserId;
    this.recentUserIp = recentUserIp;
    this.dateTime = dateTime;
    this.isUpdated = isUpdated;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getRecentUserId() {
    return recentUserId;
}

public void setRecentUserId(Long recentUserId) {
    this.recentUserId = recentUserId;
}

public String getRecentUserIp() {
    return recentUserIp;
}

public void setRecentUserIp(String recentUserIp) {
    this.recentUserIp = recentUserIp;
}

public Date getDateTime() {
    return dateTime;
}

public void setDateTime(Date dateTime) {
    this.dateTime = dateTime;
}

public int getIsUpdated() {
    return isUpdated;
}

public void setIsUpdated(int isUpdated) {
    this.isUpdated = isUpdated;
}

public void setRecentUserId(long recentUserId) {
    this.recentUserId = recentUserId;
}

public List<COAMaintenanceModel> getObj() {
    return obj;
}

public void setObj(List<COAMaintenanceModel> obj) {
    this.obj = obj;
}
@Entity
@Table(name = "ACCOUNTMAINTENANCE")
public class COAMaintenanceModel {

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

@Column(name = "ACCOUNT")
private String account;

@Column(name = "DESCRIPTION")
private String discription;

@ManyToOne
@JoinColumn(name="COACATEGORIESID")
private COACategoriesModel categoryId;

@Column(name = "POSTINGTYPE")
private int postingType;

@Column(name = "TYPICALBALANCE")
private int typicalBalance;

@Column(name = "DEBITBALANCE")
private double debitBalance;

@Column(name = "CREDITBALANCE")
private double creditBalance;

@Column(name = "NETBALANCE")
private double runningBalance;

@Column(name = "DEFAULTCURRENCYID")
private double defaultCurrencyId;

@Column(name = "ISACTIVE")
private int isActive;

@Column(name = "RECENTUSERID")
private Long recentUserId;

@Column(name = "RECENTUSERIP")
private String recentUserIp;

@Column(name = "DATETIME")
private Date dateTime;

@Column(name = "ISUPDATED")
private int isUpdated;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getAccount() {
    return account;
}

public void setAccount(String account) {
    this.account = account;
}

public String getDiscription() {
    return discription;
}

public void setDiscription(String discription) {
    this.discription = discription;
}

public COACategoriesModel getCategoryId() {
    return categoryId;
}

public void setCategoryId(COACategoriesModel categoryId) {
    this.categoryId = categoryId;
}

public int getPostingType() {
    return postingType;
}

public void setPostingType(int postingType) {
    this.postingType = postingType;
}

public int getTypicalBalance() {
    return typicalBalance;
}

public void setTypicalBalance(int typicalBalance) {
    this.typicalBalance = typicalBalance;
}

public double getDebitBalance() {
    return debitBalance;
}

public void setDebitBalance(double debitBalance) {
    this.debitBalance = debitBalance;
}

public double getCreditBalance() {
    return creditBalance;
}

public void setCreditBalance(double creditBalance) {
    this.creditBalance = creditBalance;
}

public double getRunningBalance() {
    return runningBalance;
}

public void setRunningBalance(double runningBalance) {
    this.runningBalance = runningBalance;
}

public double getDefaultCurrencyId() {
    return defaultCurrencyId;
}

public void setDefaultCurrencyId(double defaultCurrencyId) {
    this.defaultCurrencyId = defaultCurrencyId;
}

public int getIsActive() {
    return isActive;
}

public void setIsActive(int isActive) {
    this.isActive = isActive;
}

public Long getRecentUserId() {
    return recentUserId;
}

public void setRecentUserId(Long recentUserId) {
    this.recentUserId = recentUserId;
}

public String getRecentUserIp() {
    return recentUserIp;
}

public void setRecentUserIp(String recentUserIp) {
    this.recentUserIp = recentUserIp;
}

public Date getDateTime() {
    return dateTime;
}

public void setDateTime(Date dateTime) {
    this.dateTime = dateTime;
}

public int getIsUpdated() {
    return isUpdated;
}

public void setIsUpdated(int isUpdated) {
    this.isUpdated = isUpdated;
}
@Service("COAMaintenanceService")
@Transactional
public class COAMaintenanceService {


@Resource(name="sessionFactory")
private SessionFactory sessionFactory;



public void AddCOAMaintenance(COAMaintenanceModel cMaintenanceModel) {

Session session = sessionFactory.getCurrentSession();
session.save(cMaintenanceModel);

}
@Controller
public class COACategoriesController {

protected static Logger log = Logger.getLogger(COACategoriesController.class);


@Resource(name="COACategoriesService")
private COACategoriesService obj_coacs;
@Resource(name="COAMaintenanceService")
private COAMaintenanceService obj_coams;

 @RequestMapping(value = "/addCoaCategory", method = RequestMethod.POST)
 public String addCoaCategory(@RequestParam("conCatName") String coaCatName, Model model) {

     Date sysdate = null;
     String Message="";
     try{

     sysdate = new Date();

     COACategoriesModel model1 = new COACategoriesModel( coaCatName, 1, "", sysdate , 0);

     COAMaintenanceModel account =  new COAMaintenanceModel();
        account.setDiscription("Test Description");
        account.setCategoryId(model1);

        Message="Fail-First";
        obj_coacs.AddCOACategories(model1);


        Message="Fail-Second";
        obj_coams.AddCOAMaintenance (account);


        Message="Successfully Added!";
     }catch(Exception ex){
         log.error("Exception.."+ex);
         model.addAttribute("message", Message);
     }


        return "fin/category";
    }



 }
CoaCategories模型与COAMaintenanceModel之间存在一对多关系。当obj_coacs.addcoacegories(model1)在表中添加事务时,如果obj_coams.addcoams维护(account)中出现异常,它不会回滚所有事务

如何控制这一点。当所有对象成功地将事务插入表中时,提交完整的事务


最简单的方法是,使用当前场景为
@OneToMany
注释上的
级联
元素指定一个值。这将导致在保存
CAOCategoriesModel
时,
COAMaintenanceModel
被持久化。默认情况下,事务应该根据是否引发异常进行适当的提交和回滚

@Entity
@Table(name = "COACATEGORIES")
public class COACategoriesModel {

    /* Code ommitted */

    @OneToMany(mappedBy="categoryId", cascade=CascadeType.All)
    private List<COAMaintenanceModel> obj = null;

    /* Code ommitted */
}
@实体
@表(name=“COACATEGORIES”)
公共类共分类模型{
/*编码*/
@OneToMany(mappedBy=“categoryId”,cascade=CascadeType.All)
私有列表obj=null;
/*编码*/
}

不工作。实际上,我需要在最后手动提交事务