Hibernate 用annotation写一个入门程序
1、在数据库中创建一张表:student 有字段 id name age
2、建一个java项目。名hibernateTest
3、导入所需的jar包。
4、写student的实体类。并在类名前一行加上:@Entity,在getId方法上加上@id
引入的类库是: import javax.persistence.Entity;
import javax.persistence.Id;
5、写配置文件:hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernatetest</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<mapping class="com.wang.dao.Student"/>
</session-factory>
</hibernate-configuration>
6、写一个测试类:
public class AnotationTest {
public static void main(String[] args) {
Student s = new Student();
s.setId(1);
s.setAge(11);
s.setName("wang");
Configuration cf = new AnnotationConfiguration();
Session session=cf.configure().buildSessionFactory().openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
}
}