零基础接触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包!!最后,有错请指出!!菜鸟一枚还需努力!!