Hibernate中的一对一关系映射:
两张表:userinfo
create table `test`.`userinfo`(
`userid` int not null auto_increment,
`username` varchar(50),
primary key (`userid`)
);
card
create table `test`.`card`(
`cardid` int not null auto_increment,
`cardnum` int,
primary key (`cardid`)
);
注:此处列的类型一定要与后面的Bean类型一致,我就因为int与INTEGER之差苦苦查了好几天
Userinfo.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.ghost.hibernate.Userinfo" table="userinfo">
<id name="userid" type="java.lang.Integer">
<column name="userid" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="50" />
</property>
<one-to-one name="card" class="com.ghost.hibernate.Card" cascade="all"></one-to-one>
</class>
</hibernate-mapping>
Card.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.ghost.hibernate.Card" table="card">
<id name="cardid" type="java.lang.Integer">
<column name="cardid" />
<generator class="foreign" >
<param name="property">userinfo</param>
</generator>
</id>
<property name="cardnum" type="java.lang.Integer">
<column name="cardnum" />
</property>
<one-to-one name="userinfo" class="com.ghost.hibernate.Userinfo" constrained="true"></one-to-one>
</class>
</hibernate-mapping>
Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.password">ghost</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="show_sql">true</property>
<mapping resource="com/ghost/hibernate/Userinfo.hbm.xml" />
<mapping resource="com/ghost/hibernate/Card.hbm.xml" />
</session-factory>
</hibernate-configuration>
与表对应的bean文件:
Userinfo.java
package com.ghost.hibernate;
/**
* Userinfo generated by MyEclipse Persistence Tools
*/
public class Userinfo implements java.io.Serializable {
// Fields
private Integer userid;
private String username;
private Card card;
// Constructors
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
/** default constructor */
public Userinfo() {
}
/** full constructor */
public Userinfo(String username) {
this.username = username;
}
// Property accessors
public Integer getUserid() {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
}
Card.java
package com.ghost.hibernate;
public class Card implements java.io.Serializable {
private Integer cardid;
private Integer cardnum;
private Userinfo userinfo;
public Card() {
}
public Userinfo getUserinfo() {
return userinfo;
}
public void setUserinfo(Userinfo userinfo) {
this.userinfo = userinfo;
}
public Card(Integer cardnum) {
this.cardnum = cardnum;
}
public Integer getCardid() {
return this.cardid;
}
public void setCardid(Integer cardid) {
this.cardid = cardid;
}
public Integer getCardnum() {
return this.cardnum;
}
public void setCardnum(Integer cardnum) {
this.cardnum = cardnum;
}
}
HibernateSessionFactory.java
package com.ghost.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}
UserDAO.java
package com.ghost.DAO;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ghost.hibernate.HibernateSessionFactory;
import com.ghost.hibernate.Userinfo;
public class UserDAO {
public void save(Userinfo userinfo){
Session session=HibernateSessionFactory.getSession();
Transaction tx=session.beginTransaction();
session.save(userinfo);
tx.commit();
//session.close();
}
}
测试servlet:addUser.java
package com.ghost.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ghost.DAO.UserDAO;
import com.ghost.hibernate.Card;
import com.ghost.hibernate.Userinfo;
public class addUser extends HttpServlet {
public addUser() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
com.ghost.hibernate.Userinfo userinfo=new Userinfo();
userinfo.setUsername("ghost");
Card card=new Card();
card.setCardnum(new Integer(8));
card.setUserinfo(userinfo);
userinfo.setCard(card);
UserDAO userdao=new UserDAO();
userdao.save(userinfo);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void init() throws ServletException {
// Put your code here
}
}
index.jsp
<a href="servlet/addUser">add User</a>