0

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 の間には 1 対多の関係があります。AS obj_coacs.AddCOACategories(model1) はテーブルにトランザクションを追加し、obj_coams.AddCOAMaintenance (アカウント) で例外が発生した場合、すべてのトランザクションをロールバックしません。

これを制御する方法。すべてのオブジェクトがトランザクションをテーブルに正常に挿入したら、完全なトランザクションをコミットします。

現在のシーンで最も簡単な方法は何ですか

4

1 に答える 1

0

注釈のcascade要素の値を指定します。@OneToManyこれにより、が保存されCOAMaintenanceModelたときに が永続化されます。CAOCategoriesModelデフォルトでは、例外がスローされるかどうかに応じて、トランザクションは適切にコミットおよびロールバックする必要があります。

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

    /* Code ommitted */

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

    /* Code ommitted */
}
于 2013-03-31T11:48:18.910 に答える