Hibernate框架入門一

hibernate入門基礎:

   1.需引用jar包:

           hibernate-release-4.3.0.Final\hibernate-release-4.3.0.Final\lib\required   

                   1.antlr-2.7.7.jar
                   2. dom4j-1.6.1.jar
                   3.hibernate-commons-annotations-4.0.4.Final.jar
                   4. hibernate-core-4.3.0.Final.jar
                   5. hibernate-jpa-2.1-api-1.0.0.Final.jar
                  6.  jandex-1.1.0.Final.jar

                  7.  javassist-3.18.1-GA.jar

                 8.  /jboss-logging-3.1.3.GA.jar
                 9.  jboss-logging-annotations-1.2.0.Beta1.jar
                10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar

 裏面的jar文件都是最基本的

    另外還有一些依賴的的jar包: 

          比如:需要引入相應數據庫的驅動jar包

                        mysql-connector-java-5.1.16-bin.jar

     2.創建配置文件hibernate.cfg.xml

              

<?xml version="1.0" encoding="utf-8"?>
<!-- 根標籤 -->
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
	<hibernate-configuration>
<session-factory>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/hiber?useUincode=true&characterEncoding=UTF-8
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>

	<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
3.創建解析hibernate.cfg.xml的HibernateSessionFactory工廠

package www.csdn.net.hibernate1.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * @author Yuan WenJ
 *
 */
public class HibernateSessionFactory {
  static Configuration cfg;
  static SessionFactory sessionFactory;
  static ServiceRegistry serviceRegistry;
  
  static{
//	  解析hibernate.cfg.xml
	  cfg=new Configuration().configure();
//	  創建服務註冊對象   StandardServcieRegister     StandardServiceRegistryBuilder()
	  serviceRegistry=new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
//	  創建sessionFactory工廠對象
	  sessionFactory=cfg.buildSessionFactory(serviceRegistry);
  } 
  public static Session getSession(){
	 return sessionFactory.openSession();
	  
  }
}
下面以User類爲例

       創建User類

package www.csdn.net.hibernate1.bean;
public class User {
	private Integer id;
	private String name;
	private String sex;
	private Integer age;
	public User() {
		super();
	}
	public User(Integer id, String name, String sex, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age="
				+ age + "]";
	}
}

創建解析User類的User.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="www.csdn.net.hibernate1.bean.User" table="user" catalog="hiber">
       <id name="id" column="id">
         <generator class="native"/>
       </id>
       <property name="name" column="name"/>
        <property name="sex" column="sex"/>
         <property name="age" column="age"/>
    </class>
</hibernate-mapping>

創建完User.hbm.xml後須在hibernate.cfg.xml中配置。如圖所示:


創建baseDao接口和UserDao接口

package www.csdn.net.hibernate1.dao;
import java.util.List;
public interface BaseDao<T, PK> {
	T findById(PK id);
	void deleteById(PK id)throws Exception;
	void delete(T entity)throws Exception;
	void deletes(String ids[])throws Exception;
	void update(T entity)throws Exception;
	void insert(T entity)throws Exception;
	List<T> findAll();
}
package www.csdn.net.hibernate1.dao;
import www.csdn.net.hibernate1.bean.User;
public interface UserDao extends  BaseDao<User, Integer>{

}

創建UserDaoImpl

    
 package www.csdn.net.hibernate1.dao.impl;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import www.csdn.net.hibernate1.bean.User;
import www.csdn.net.hibernate1.dao.UserDao;
import www.csdn.net.hibernate1.util.HibernateSessionFactory;

public class UserDaoImpl implements UserDao {

	@Override
	public User findById(Integer id) {
		return (User) HibernateSessionFactory.getSession().get(User.class, id);
	}
	@Override
	public void deleteById(Integer id) throws Exception {
		// 獲取session
		Session session = HibernateSessionFactory.getSession();
		// 開啓事物
		Transaction transaction = session.beginTransaction();
		// 通過id刪除
		session.delete(findById(id));
		// 提交事物
		transaction.commit();
		// 關閉session
		session.close();
	}
	@Override
	public void delete(User entity) throws Exception {
		// 獲取session
		Session session = HibernateSessionFactory.getSession();
		// 開啓事物
		Transaction transaction = session.beginTransaction();
		// 刪除事物
		session.delete(entity);
		// 提交事物
		transaction.commit();
		// 關閉session
		session.close();
	}
	@Override
	public void deletes(String[] ids) throws Exception {
		

	}

	@Override
	public void update(User entity) throws Exception {
		// 獲取session
		Session session = HibernateSessionFactory.getSession();
		// 開啓事物
		Transaction transaction = session.beginTransaction();
		// 更新事物
		session.update(entity);
		// 提交事物
		transaction.commit();
		// 關閉session
		session.close();

	}

	@Override
	public void insert(User entity) throws Exception {
		// 獲取session
		Session session = HibernateSessionFactory.getSession();
		// 開啓事物
		Transaction ts = session.beginTransaction();
		// 保存session
		session.save(entity);
		// 提交事物
		ts.commit();
		// 關閉session
		session.close();
	}

	@Override
	public List<User> findAll() {
		return HibernateSessionFactory.getSession().createQuery("from User")
				.list();
	}
}

測試後成功即可

創建測試方法:(測試方法非常重要,如果不測試有可能出現一些異常,錯誤造成我們在寫代碼過程中的異常或錯誤。)

package www.csdn.net.hibernate1.junit;

import java.util.List;
import org.junit.Test;
import www.csdn.net.hibernate1.bean.User;
import www.csdn.net.hibernate1.dao.UserDao;
import www.csdn.net.hibernate1.dao.impl.UserDaoImpl;

public class UserTest {
	private UserDao userDao = new UserDaoImpl();
	@Test
	public void insert() throws Exception {
		User entity = new User(null, "zz", "f", 21);
		userDao.insert(entity);
	}
	@Test
	public void update() throws Exception {
		User entity = userDao.findById(11);
		entity.setName("yy44");
		entity.setSex("f");
		entity.setAge(21);
		userDao.update(entity);
	}
	@Test
	public void delete() throws Exception {
		userDao.deleteById(3);
	}
	@Test
	public void findAll() {
		List<User> users = userDao.findAll();
		for (User u : users) {
			System.out.println(u.toString());
		}
	}
	@Test
	public void findById() {
		userDao.findById(1);
	}
	@Test
	public void deleteById() throws Exception {
		userDao.deleteById(1);
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章