零基础接触hibernate,在学习的过程中接触到了Annotation(翻译过来“注释”)。在学习过程中, 并不知道annotation怎么发展来的,但通过对比操作,发现了Annotation在编码中简化了对映射文件的编写(虽然很大程度上是copy过来的)!!话不多上,直接将编码过程贴上(菜鸟,写不出高大上的东西,此乃无奈之举)!!
创建数据库
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./>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包!!最后,有错请指出!!菜鸟一枚还需努力!!
原标题:hibernate初入门2
关键词:Hibernate