[Hibernate] - Annotations - One To One
Hibernate annotation 一对一的两种实现:
1)幅表中有主表的主键ID做为引用
2)幅表的主键即为主表的ID
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property> <property name="connection.username">root</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate‘s automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping class="com.my.bean.User"/> <mapping class="com.my.bean.UserCard"/> <mapping class="com.my.bean.UserInfo"/> </session-factory> </hibernate-configuration>
HibernateUtil.java
package com.my.dao.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); return configuration.configure().buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Java Beans:
package com.my.bean; import java.util.Date; import javax.persistence.*; @Entity @Table(name="user") public class User { @Id @GeneratedValue @Column(name="user_id", nullable=false) private long userID; @Column(name="user_name", length=100, nullable=false) private String userName; @Column(name="create_time", nullable=false) private Date createTime; @OneToOne(mappedBy="user") private UserCard userCard; @OneToOne(cascade=CascadeType.ALL) @PrimaryKeyJoinColumn private UserInfo userInfo; public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public UserCard getUserCard() { return userCard; } public void setUserCard(UserCard userCard) { this.userCard = userCard; } }
package com.my.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name="user_card") public class UserCard { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="card_id", nullable=false) private long cardID; @OneToOne @JoinColumn(name="user_id") private User user; @Column(name="card_name", nullable=false) private String cardName; public long getCardID() { return cardID; } public void setCardID(long cardID) { this.cardID = cardID; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } }
package com.my.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @Table(name="user_info") public class UserInfo { @Id @GeneratedValue(generator="userInfoForeignKey") @GenericGenerator(name="userInfoForeignKey", strategy="foreign", parameters=@Parameter(name="property", value="user")) @Column(name="user_id", nullable=false) private long userID; @Column(name="message", nullable=false) private String Message; @OneToOne(mappedBy="userInfo") private User user; public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getMessage() { return Message; } public void setMessage(String message) { Message = message; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
测试:
package com.my.init; import java.util.Date; import org.hibernate.Session; import org.hibernate.Transaction; import com.my.bean.User; import com.my.bean.UserCard; import com.my.bean.UserInfo; import com.my.dao.util.HibernateUtil; public class Test { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); try { //--------------------------------------------------------- // The first method //--------------------------------------------------------- // add user User user = new User(); user.setUserName("Robin"); user.setCreateTime(new Date()); // add user card UserCard userCard = new UserCard(); userCard.setCardName("BBC"); // add user card to user object user.setUserCard(userCard); userCard.setUser(user); //--------------------------------------------------------- // The second method //--------------------------------------------------------- UserInfo userInfo = new UserInfo(); userInfo.setMessage("Message"); userInfo.setUser(user); //--------------------------------------------------------- // save //--------------------------------------------------------- session.save(user); session.save(userCard); session.save(userInfo); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } session.close(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。