测试类:
@Test
public void testSaveStudent(){
Configuration cfg = new Configuration();
cfg.configure();
Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
Transaction tx=session.beginTransaction();
// cfg.addClass(cqu.edu.entity.Students.class);
Students student1=new Students("S0000001","张三","男",new Date(),"重庆");
Students student2=new Students("S0000002","李四","男",new Date(),"海南");
Students student3=new Students("S0000003","王五","男",new Date(),"四川");
session.save(student1);
session.save(student2);
session.save(student3);
tx.commit();
}
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 >
<property name ="connection.username">root</property>
<property name ="connection.password">123456</property>
<property name= "connection.driver_class">com.mysql.jdbc.Driver </property > <!-- 驱动路径 -->
<property name= "connection.url">jdbc:mysql://127.0.0.1:3306/students_database?useUnicode=true&characterEncoding=UTF-8</property ><!-- 连接数据库字符串 -->
<property name= "hibernate.dialect">org.hibernate.dialect.MySQLDialect</property >
<property name ="show_sql">true</property> <!-- 显示SQL语句 -->
<property name ="format_sql">true</property>
<property name ="hbm2ddl.auto">update</property>
<!-- 配置使用session.getCurrentSession()方法 -->
<property name= "hibernate.current_session_context_class" >thread</property >
<property name="javax.persistence.validation.mode">none</property>
<!-- hbm.xml -->
<mapping resource ="cqu/edu/entity/Users.hbm.xml"/>
<mapping resource ="cqu/edu/entity/yStudents.hbm.xml"/>
</session-factory >
</hibernate-configuration>
相应的Students.hbm.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cqu.edu.entity.Students" table="STUDENTS">
<id name="sid" type="java.lang.String" length="8">
<generator class="assigned"/>
</id>
<property name="sname" type="java.lang.String"></property>
<property name="gender" type="java.lang.String"></property>
<property name="birthday" type="java.util.Date"></property>
<property name="address" type="java.lang.String"></property>
</class>
</hibernate-mapping>
谢谢!
相关分类