日期:2014-05-19  浏览次数:20890 次

hibernate一对多双向关联总是不成功,求助啊
数据库中表是这样的一个user对应多个bankAccount,为了运行成功,没有加外键
Java code

public class User {
    private int UserId;
    private String Username;
    private String Password;
    private Date RegisterTime;
    private Set<BankAccount> BankAccounts = new HashSet<BankAccount>();
}

public class BankAccount {
    private int CardNumber;
    private String AccountName;
    private User BankUser;
}



XML code

<hibernate-mapping>

<class name="Model.BankAccount" table="bankaccount">

<id name="CardNumber" type="int" column="CardNumber" >
<generator class="assigned"/>
</id>
<property name="AccountName" column="AccountName" />
<many-to-one name="BankUser" column="UserId" class="Model.User"/>
</class>
</hibernate-mapping>



<hibernate-mapping>

<class name="Model.User" table="user">

<id name="UserId" type="int" column="UserId" >
<generator class="assigned"/>
</id>
<property name="Username" column="Username" />
<property name="Password" column="Password" />
<property name="RegisterTime" type="timestamp" column="RegisterTime"/>
<set name="BankAccounts" table="bankaccount" inverse="true">
    <key>
        <column name="UserId"/>
    </key>
    <one-to-many class="Model.BankAccount" />
</set>
</class>
</hibernate-mapping>






想同时插入一个user 和一个bank Account

Java code

public void saveUserAndBank(String username, String password, int CardNo, String AccountName) {
        session.beginTransaction();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRegisterTime(new Date());
                
        // create bank account
        BankAccount bankAcc = new BankAccount();
        bankAcc.setCardNumber(CardNo);
        bankAcc.setAccountName(AccountName);
        session.save(user);
        session.save(bankAcc);
        bankAcc.setBankUser(user);
        user.getBankAccounts().add(bankAcc);
        session.getTransaction().commit();       
    }





可是每次运行这个后saveUserAndBank("m.wu", "123456", 2222, "Mervyn Wu");,只在数据中插入了两条数据
Bank Account
2222 Mervyn Wu 0
User
1 m.wu 123456 2012-09-29 13:42:50

Bank Account数据没有把 UserID设为1,这是什么情况
如果我加在BankAccount中加入UserID外键 update delete 都设为cascade,就有运行错误
 Cannot add or update a child row: a foreign key constraint fails (`lottery/bankaccount`, CONSTRAINT `BankUserId` FOREIGN KEY (`UserId`) REFERENCES `user` (`UserId`) ON DELETE CASCADE ON UPDATE CASCADE)

求助,我究竟是哪里错了?

------解决方案--------------------
Java code
 session.save(user);
        session.save(bankAcc);
        bankAcc.setBankUser(user);

------解决方案--------------------
你的事务呢
------解决方案--------------------
你这个有这几个地方的问题:
1,你的命名不规范,属性的开头两个字母应该用小写
2,你的配置也有问题,<set name="BankAccounts" table="bankaccount" inverse="true">
<key>
<column name="UserId"/>