簡體   English   中英

Spring MVC和Hibernate應該按需保存事務

[英]spring mvc and hibernate should save the transaction on demand

我正在使用Spring MVC和Hibernate。 以下是我的代碼示例。

applicationContext.xml

<context:annotation-config />
<context:component-scan base-package="com.soft.erp" />
<mvc:annotation-driven /> 
<import resource="hibernate-context.xml" />

config.properties

app.jdbc.driverClassName=com.mysql.jdbc.Driver
app.jdbc.url=jdbc:mysql://localhost:3306/besoin
app.jdbc.username=root
app.jdbc.password=7886
hibernate.config=/WEB-INF/hibernate.cfg.xml

hibernate.cfg.xml

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>

hibernate-context.xml

    <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" />

COACategoriesModel.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;
}

COAMaintenanceModel.java

@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;
}

COACategoriesService.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

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


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



public void AddCOAMaintenance(COAMaintenanceModel cMaintenanceModel) {

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

}

}

COACategoriesController.java

@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";
    }



 }

COACategoriesModel與COAMaintenanceModel之間存在一對多的關系。 AS obj_coacs.AddCOACategories(model1)將事務添加到表中,如果obj_coams.AddCOAMaintenance(帳戶)中發生異常,則不會回滾所有事務。

如何控制這個。 當所有對象成功將事務插入表中后,再提交完整的事務。

在當前場景中,最簡單的方法是什么

@OneToMany批注上為cascade元素指定一個值。 這將導致COAMaintenanceModel時,要堅持CAOCategoriesModel被保存。 默認情況下,事務應根據是否引發異常來適當地提交和回滾。

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

    /* Code ommitted */

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

    /* Code ommitted */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM