"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
org.hibernate.dialect.MySQLDialect
< xml version='1.0' encoding='UTF-8' >
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
jdbc:mysql://localhost:3306/test
com.mysql.jdbc.Driver
org.hibernate.dialect.MySQLDialect
8.写测试类(TestHibernate)
测试类主要用于测试hibernate的增删查改功能!
hibernate封装了SQL语句,只需要调用hibernate的API就可以实现增删查改,比SQL语句简便
增加save方法:
[java]
package com.TodayMZ.hiber.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.TodayMZ.hiber.po.User;
public class TestHibernate {
@Test
public void test1(){
User user=new User();
user.setLoginName("todayMZ");
user.setName("today");
user.setPassword("1234");
Configuration conf=new Configuration();/*调用HibernateAPI,装载Hibernate配置文件*/
conf.configure();/*装载默认配置文件,所过指定则装载conf.configure(new File("abc.xml"););*/
SessionFactory factory=conf.buildSessionFactory();/*创建SessionFactory*/
Session session=factory.openSession(); /*创建Session*/
Transaction tx=session.getTransaction();/*获取事物*/
tx.begin(); /*开启事物*/
session.save(user);/*插入数据*/
tx.commit(); /*提交事物*/
session.close();/*关闭事物*/
}
}
package com.TodayMZ.hiber.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.TodayMZ.hiber.po.User;
public class TestHibernate {
@Test
public void test1(){
User user=new User();
user.setLoginName("todayMZ");
user.setName("today");
user.setPassword("1234");
Configuration conf=new Configuration();/*调用HibernateAPI,装载Hibernate配置文件*/
conf.configure();/*装载默认配置文件,所过指定则装载conf.configure(new File("abc.xml"););*/
SessionFactory factory=conf.buildSessionFactory();/*创建SessionFactory*/
Session session=factory.openSession(); /*创建Session*/
Transaction tx=session.getTransaction();/*获取事物*/
tx.begin(); /*开启事物*/
session.save(user);/*插入数据*/
tx.commit(); /*提交事物*/
session.close();/*关闭事物*/
}
}
更改Update方法:
[java]
package com.TodayMZ.hiber.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.TodayMZ.hiber.po.User;
public class TestHibernate {
@Test
public void test1(){
User user=new User();
user.setId(1);
user.setLoginName("todayMZ