Hibernate操作没有主键数据表

来源:互联网 发布:mac唇膏专柜 编辑:程序博客网 时间:2024/04/27 19:29

在数据库中中间表往往可能没有主键,而Hibernate检索的时候是根据主键检索的,这样就无法直接检索中间表中的数据。对于这种情况Hibernate会自动生成一个主键辅助类来辅助检索,下面看具体使用方法。

数据库存在数据表region表存有两个字段,一个city字段,一个code字段,city字段存放城市名,code字段存放城市代码。没有指定主键。

这是使用Hibernate的反向工程自动创建POJO类和映射关系。同时会自动生成一个辅助类。

首先看一下POJO类。

public class RegionId implements java.io.Serializable {// Fieldsprivate String city;private String eamcode;// Constructors/** default constructor */public RegionId() {}/** full constructor */public RegionId(String city, String eamcode) {this.city = city;this.eamcode = eamcode;}// Property accessorspublic String getCity() {return this.city;}public void setCity(String city) {this.city = city;}public String getEamcode() {return this.eamcode;}public void setEamcode(String eamcode) {this.eamcode = eamcode;}}
然后看他的辅助类

public class Region implements java.io.Serializable {// Fieldsprivate RegionId id;// Constructors/** default constructor */public Region() {}/** full constructor */public Region(RegionId id) {this.id = id;}// Property accessorspublic RegionId getId() {return this.id;}public void setId(RegionId id) {this.id = id;}}
我们可以看到这个辅助类中只有一个RegionId类型的成员id。

下面看一下他的映射关系。

<hibernate-mapping>    <class name=Region" table="region" schema="dbo">        <composite-id name="id" class="RegionId">            <key-property name="city" type="java.lang.String">                <column name="city" length="20" />            </key-property>            <key-property name="eamcode" type="java.lang.String">                <column name="eamcode" length="20" />            </key-property>        </composite-id>    </class></hibernate-mapping>
上述类和映射文件都是Hibernate反向工程自动生成的。

下面看一下如何操作数据表,这里已查询为例:

public List findByProperty(String propertyName, Object value) {try {String queryString = "from Region as model where model."+ propertyName + "= ?";Query queryObject = getSession().createQuery(queryString);queryObject.setParameter(0, value);return queryObject.list();} catch (RuntimeException re) {throw re;}}
然后看测试类

public static void main(String[] args) {RegionDAO df = new RegionDAO();List list = df.findByProperty("id.city", "3701");Region u = (Region) list.get(0);System.out.println(u.getId().getcode());}
这里要注意的是操作的一直是Hibernate生成的辅助类,但是在传数据时还有获取数据时都是从Region类的Id中获取指定的RegionId。





0 0
原创粉丝点击