今天第一次用hibernate ,发现用起来比较繁琐,不知道大家感觉怎么样...
首先是我遇到数据库复合主键的问题:
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">jdbc:mysql://localhost/netshop</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="connection.password">a123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="show_sql">true</property>
<mapping resource="WebService/Orders_detail.hbm.xml" />------------------------------这里第一次的时候忘了加了
</session-factory>
</hibernate-configuration>
<hibernate-mapping>
<class name="WebService.Orders_detail" table="orders_detail"> <!-- 类和表对应 -->-------------
WebService.Orders_detail类中必须有一个默认无参构造函数,否则会出现CGLIB Enhancement failed。。。错误
<composite-id name="pk" class="WebService.Orders_detailpk>--------------------------------
一开始class属性没写,找了半天才发现错误
<key-property name="orderid" column="orderid" ><!-- 主键 -->
<!-- <generator class="assigned" /> --><!-- 主键生成策略,assigned表示由用户赋值 -->
</key-property>
<key-property name="rnum" column="rnum" ><!-- 主键 -->
<!-- <generator class="assigned" /> --><!-- 主键生成策略,assigned表示由用户赋值 -->
</key-property>
</composite-id>
<property name="goods_id" column="goods_id"/>
<property name="goods_name" column="goods_name"/>
<property name="goods_price" column="goods_price"/>
<property name="qty" column="qty"/>
</class>
</hibernate-mapping>
配置文件写好后,在类中可以这样调用:
Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Orders_detailpk pk=new Orders_detailpk();
pk.setOrderid("10202321");
pk.setRnum(5);
Orders_detail order=(Orders_detail)session.load(Orders_detail.class,pk);
System.out.println(order.getGoods_id());
System.out.println(order.getGoods_name());
System.out.println(order.getGoods_price());
System.out.println(order.getQty());
总结:hibernate用起来似乎没发现很方便。。