hibernate框架自动创建数据库表格

1.修改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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://127.0.0.1:6789/ucm
</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">SQLNAME</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
<!-- 添加自动创建数据库表格的配置 -->
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/cimstech/test/Teams.hbm.xml" />

</session-factory>

</hibernate-configuration>

2.修改Teams.hbm.xml数据库表映射配置文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->

 <!--添加所要创建的数据库表格的映射配置 --> 
<hibernate-mapping>
    <class name="com.cimstech.test.Teams" table="teams" catalog="ucm">
        <composite-id name="id" class="com.cimstech.test.TeamsId">
            <key-property name="player" type="java.lang.String">
                <column name="player" length="10" />
            </key-property>
            <key-property name="team" type="java.lang.String">
                <column name="team" length="9" />
            </key-property>
        </composite-id>
    </class>    

</hibernate-mapping>

3.创建实体Bean(映射类)

(1)Teams 类

package com.cimstech.test;


public class Teams implements java.io.Serializable {


// Fields


private TeamsId id;
// Constructors


/** default constructor */
public Teams() {
}


/** full constructor */
public Teams(TeamsId id) {
this.id = id;
}


// Property accessors


public TeamsId getId() {
return this.id;
}


public void setId(TeamsId id) {
this.id = id;
}


}


(2)TeamsId 类

package com.cimstech.test;


public class TeamsId implements java.io.Serializable {


// Fields


private String player;
private String team;


// Constructors


/** default constructor */
public TeamsId() {
}


/** full constructor */
public TeamsId(String player, String team) {
this.player = player;
this.team = team;
}


// Property accessors


public String getPlayer() {
return this.player;
}


public void setPlayer(String player) {
this.player = player;
}


public String getTeam() {
return this.team;
}


public void setTeam(String team) {
this.team = team;
}


public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TeamsId))
return false;
TeamsId castOther = (TeamsId) other;


return ((this.getPlayer() == castOther.getPlayer()) || (this
.getPlayer() != null && castOther.getPlayer() != null && this
.getPlayer().equals(castOther.getPlayer())))
&& ((this.getTeam() == castOther.getTeam()) || (this.getTeam() != null
&& castOther.getTeam() != null && this.getTeam()
.equals(castOther.getTeam())));
}


public int hashCode() {
int result = 17;


result = 37 * result
+ (getPlayer() == null ? 0 : this.getPlayer().hashCode());
result = 37 * result
+ (getTeam() == null ? 0 : this.getTeam().hashCode());
return result;
}


}


(3)TeamsDAO


package com.cimstech.test;

import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TeamsDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(TeamsDAO.class);


// property constants


public void save(Teams transientInstance) {
log.debug("saving Teams instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}


public void delete(Teams persistentInstance) {
log.debug("deleting Teams instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}


public Teams findById(com.cimstech.test.TeamsId id) {
log.debug("getting Teams instance with id: " + id);
try {
Teams instance = (Teams) getSession().get(
"com.cimstech.test.Teams", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}


public List findByExample(Teams instance) {
log.debug("finding Teams instance by example");
try {
List results = getSession()
.createCriteria("com.cimstech.test.Teams")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}


public List findByProperty(String propertyName, Object value) {
log.debug("finding Teams instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Teams as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}


public List findAll() {
log.debug("finding all Teams instances");
try {
String queryString = "from Teams";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}


public Teams merge(Teams detachedInstance) {
log.debug("merging Teams instance");
try {
Teams result = (Teams) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}


public void attachDirty(Teams instance) {
log.debug("attaching dirty Teams instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}


public void attachClean(Teams instance) {
log.debug("attaching clean Teams instance");
try {
getSession().buildLockRequest(LockOptions.NONE).lock(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}

4.执行一个查询数据的操作即可

public void test2() throws Exception 
{
try
{

Session session = HibernateSessionFactory.getSession();

String sql = "select * from Teams";
List list = session.createSQLQuery(sql).
addScalar("team", StandardBasicTypes.STRING)
.addScalar("player",StandardBasicTypes.STRING).list();
Iterator iter = list.iterator();
while(iter.hasNext())
{
Object[] objs =(Object[])iter.next();
System.out.println("team="+objs[0]);
System.out.println("player="+objs[1]);
System.out.println("--------------------------");
}
}
catch(Exception e)
{
throw e;
}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值