hibernate初入门2--Annotation

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

hibernate初入门2--Annotation零基础接触hibernate,在学习的过程中接触到了Annotation(翻译过来“注释”)。在学习过程中, 并不知道annotation怎么发展来的,但通过对比操作,发现了Annotation在编码中简化了对映射文件的编写(虽然很大程度上是copy过来的)!!话不多上,直接将编码过程贴上(菜鸟,写不出高大上的东西,此乃无奈之举)!!

创建数据库

创建实体类Teacher.java

1 package com.hibernate.Exp150704; 2 3 import javax.persistence.Entity; 4 import javax.persistence.Id; 5 6 @Entity//Annotation的特别之处,由于注明此类为实体类 7 public class Teacher { 8 //@Id 此处亦可放置注释,用于指代主键,但如果get方法为非标准方式定义的,如通过getSid()获取Id 则可能出现问题!! 9 PRivate int id;10 private String name;11 private String title;12 13 @Id//表示此为获得实体类所对应的数据库的主键 14 public int getId() {15 return id;16 }17 public void setId(int id) {18 this.id = id;19 }20 public String getName() {21 return name;22 }23 public void setName(String name) {24 this.name = name;25 }26 public String getTitle() {27 return title;28 }29 public void setTitle(String title) {30 this.title = title;31 }32 33 34 }

将实体类添加到配置文件hibernate.cfg.xml中

1 <?xml version='1.0' encoding='utf-8'?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <property name="connection.driver_class">com.MySQL.jdbc.Driver</property> 8 <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> 9 <property name="connection.username">root</property>10 <property name="connection.passWord">TAN19911104</property>11 12 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>13 14 <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>15 16 <property name="show_sql">true</property>17 18 <mapping resource="com/hibernate/Exp150702/Student.hbm.xml"/>19 <mapping class="com.hibernate.Exp150704.Teacher"/> /*此处为使用Annotation时,配置文件对映射的定义形式 为class = "实体类" */20 </session-factory>21 </hibernate-configuration>

测试类 TestDemo.java

1 package com.hibernate.Exp150704; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.AnnotationConfiguration; 6 import org.hibernate.cfg.Configuration; 7 import org.junit.Test; 8 9 10 public class TestDemo {11 12 @Test 13 @SuppressWarnings("deprecation")14 public void test(){15 16 Teacher t = new Teacher();17 t.setId(1);18 t.setName("小元");19 t.setTitle("proffessional");20 //只有AnnotationConfiguration能够获取实体类中使用的Annotation映射21 Configuration cfg = new AnnotationConfiguration();22 SessionFactory sf = cfg.configure().buildSessionFactory();23 Session session = sf.openSession();24 session.beginTransaction();25 session.save(t);26 session.getTransaction().commit();27 session.close();28 }29 }

至此,实验结束!!当然在使用Annotation之前,需加入与Annotation相关的jar包!!本人使用了如下jar包!!最后,有错请指出!!菜鸟一枚还需努力!!

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航