模型user,address
address中有一个字段为user_id与user的userid进行外键关联
user sql
CREATE TABLE `NewTable` (`userid` int(11) NOT NULL AUTO_INCREMENT ,`account` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,PRIMARY KEY (`userid`))ENGINE=InnoDBDEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ciAUTO_INCREMENT=40ROW_FORMAT=COMPACT;
address sql
CREATE TABLE `NewTable` (`addressid` int(11) NOT NULL AUTO_INCREMENT ,`addressinfo` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`user_id` int(11) NULL DEFAULT NULL ,PRIMARY KEY (`addressid`),FOREIGN KEY (`user_id`) REFERENCES `user` (`userid`) ON DELETE RESTRICT ON UPDATE RESTRICT,INDEX `userud` (`user_id`) USING BTREE )ENGINE=InnoDBDEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ciAUTO_INCREMENT=47ROW_FORMAT=COMPACT;
user
package dto;import java.util.HashSet;import java.util.Set;public class User { private int userid; private String account; private String password; private Address address; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
user.hbm.xml
address
package dto;public class Address { private Integer addressid; private User user; private String addressinfo; public Integer getAddressid() { return addressid; } public void setAddressid(Integer addressid) { this.addressid = addressid; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getAddressinfo() { return addressinfo; } public void setAddressinfo(String addressinfo) { this.addressinfo = addressinfo; }}
address.hbm.xml
main
package test;import org.hibernate.Session;import org.hibernate.Transaction;import util.HibernateUtil;import dto.Address;import dto.User;public class UserTest { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Address a = new Address(); a.setAddressinfo("america"); Address a2 = new Address(); a2.setAddressinfo("china"); User user = new User(); user.setAccount("jack"); user.setPassword("111111"); User user2 = new User(); user2.setAccount("peter"); user2.setPassword("111111"); a.setUser(user2); a.setUser(user); a2.setUser(user2); session.save(user); session.save(user2); session.save(a); session.save(a2); tx.commit(); HibernateUtil.closeSession(); }}