標籤:hibernate 增刪改查 小測試
好久沒有敲過了,來熟悉下hibernate,做了個小測試。
-
測試專案結構圖,關於匯入jar包,可以參考 http://zhuws.blog.51cto.com/11134439/1932652
650) this.width=650;" src="https://s3.51cto.com/wyfs02/M02/98/30/wKioL1k4pqKwOpY0AAA2_UaBpfE211.png" title="AAA.png" alt="wKioL1k4pqKwOpY0AAA2_UaBpfE211.png" />
2.hibernate.cfg.xml 配置
<!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="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hibernate.connection.username">ssh</property> <property name="hibernate.connection.password">ssh</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property> <!-- 方言 --> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- 可視化sql --> <property name="hibernate.show_sql">true</property> <!-- 格式化sql,自動對可視化sql換行,對齊 --> <property name="hibernate.format_sql">true</property> <!-- 為getCurrentSession添加配置,保證事務中公用義個session --> <property name="current_session_context_class">thread</property> <!-- 對應檔配置 --> <mapping resource="User.hbm.xml"/> </session-factory></hibernate-configuration>
3.User.hbm.xml配置
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><!-- name:是實體 table是表名稱 --><class name="com.hib.entity.Users" table="TEST_USER"><id name="id"><!-- 主鍵自增策略,hibernate提供了幾種,這裡測試,先寫一個,後面會補充 --><!-- increment:主鍵自增策略 --><generator class="increment"></generator></id><!-- name:是實體中屬性的名稱,column:是表中欄位的名稱,type是資料類型 在這裡發現後面的 pass和 address 沒有寫column和type如果表欄位和實體屬性名稱一致,可以省略不寫--><property name="name" column="name" type="java.lang.String"/><property name="pass"/><property name="address"/></class></hibernate-mapping>
4. 實體類Users
package com.hib.entity;public class Users {private Integer id;private String name;private String pass;private String address;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 getPass() {return pass;}public void setPass(String pass) {this.pass = pass;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public Users(Integer id, String name, String pass, String address) {super();this.id = id;this.name = name;this.pass = pass;this.address = address;}public Users() {super();}@Overridepublic String toString() {return "Users [id=" + id + ", name=" + name + ", pass=" + pass + ", address=" + address + "]";}}
5. 建表,這裡只是測試,所以類型長度就不要在意了。
650) this.width=650;" src="https://s5.51cto.com/wyfs02/M00/98/30/wKioL1k4py3RB2RvAABcpM184Go308.png" title="BBBB.png" alt="wKioL1k4py3RB2RvAABcpM184Go308.png" />
6.userDao
package com.hib.userDao;import com.hib.entity.Users;public interface UserDao {// 根據使用者id查詢使用者資訊public Users queryUserById(Integer id);// 插入使用者public void insertUser(Users user);// 刪除使用者public void deleteUser(Integer id);// 更新使用者資料public void updateUser(Users user);}
7.userDaoImpl
package com.hib.userDao.impl;import org.hibernate.Session;import com.hib.entity.Users;import com.hib.userDao.UserDao;import com.hib.util.HibUtil;public class UserDaoImpl implements UserDao{// 根據使用者ID查詢@Overridepublic Users queryUserById(Integer id) {Session session = HibUtil.getSession();Users users = session.get(Users.class, id);return users;}// 插入資料@Overridepublic void insertUser(Users user) {Session session = HibUtil.getSession();session.save(user);}// 根據ID 刪除@Overridepublic void deleteUser(Integer id) {Session session = HibUtil.getSession();Users users = session.get(Users.class, id);session.delete(users);}// 更新@Overridepublic void updateUser(Users user) {Session session = HibUtil.getSession();session.update(user);}}
8.userService
package com.hib.services;import com.hib.entity.Users;public interface UserServices {// 根據使用者id查詢使用者資訊public Users queryUserById(Integer id);// 插入使用者public void insertUser(Users user);// 刪除使用者public void deleteUser(Integer id);// 更新使用者資料public void updateUser(Users user);}
9.userServiceImpl
package com.hib.services.impl;import org.hibernate.Session;import org.hibernate.Transaction;import com.hib.entity.Users;import com.hib.services.UserServices;import com.hib.userDao.UserDao;import com.hib.userDao.impl.UserDaoImpl;import com.hib.util.HibUtil;public class UserServicesImpl implements UserServices{private UserDao ud = new UserDaoImpl();@Overridepublic Users queryUserById(Integer id) {Session session = null;Transaction tx = null;Users user = null;try {session = HibUtil.getSession();tx = session.beginTransaction();user = ud.queryUserById(id);tx.commit();} catch (Exception e) {tx.rollback();throw new RuntimeException("查詢出錯!");}return user;}@Overridepublic void insertUser(Users user) {Session session = null;Transaction tx = null;try {session = HibUtil.getSession();tx = session.beginTransaction();ud.insertUser(user);tx.commit();} catch (Exception e) {tx.rollback();throw new RuntimeException("插入錯誤!");}}@Overridepublic void deleteUser(Integer id) {Session session = null;Transaction tx = null;try {session = HibUtil.getSession();tx = session.beginTransaction();ud.deleteUser(id);tx.commit();} catch (Exception e) {tx.rollback();throw new RuntimeException("刪除錯誤!");}}@Overridepublic void updateUser(Users user) {Session session = null;Transaction tx = null;try {session = HibUtil.getSession();tx = session.beginTransaction();ud.updateUser(user);tx.commit();} catch (Exception e) {tx.rollback();throw new RuntimeException("更新錯誤!");}}}
10.util 工具類
package com.hib.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;/** * * @author admin *生產session */public class HibUtil {private static Configuration cfg = new Configuration().configure();private static SessionFactory factory = cfg.buildSessionFactory();public static Session getSession(){return factory.getCurrentSession();}public static Session openSession(){return factory.openSession();}}
11.測試
package com.hib.test;import org.junit.Test;import com.hib.entity.Users;import com.hib.services.UserServices;import com.hib.services.impl.UserServicesImpl;public class TestUser {private UserServices us = new UserServicesImpl();// 插入資料@Testpublic void insert(){us.insertUser(new Users(null, "小李飛刀", "xlfd", "china"));}// 測試查詢@Testpublic void query(){Users users = us.queryUserById(1);System.out.println(users);}// 更新@Testpublic void update(){us.updateUser(new Users(1, "小李飛刀他媽", "xlfdtm", "AAAAA"));}// 刪除@Testpublic void delete(){us.deleteUser(1);}}
12. dao 是和資料打交道
service 是控制業務,事務,實際開發業務就是在這裡寫
注意: 這裡用的資料庫是oracle,測試時候,需要在hibernate.cfg.xml 中把資料庫名稱和密碼修改為自己的。
本文出自 “永恒之光” 部落格,請務必保留此出處http://zhuws.blog.51cto.com/11134439/1933294
hibernate 增刪改查小測試