【SSH三大架構】Hibernate基礎第五篇:利用Hibernate完畢簡單的CRUD操作

來源:互聯網
上載者:User

標籤:mysq   on()   action   uniq   auto   com   java   ssh   利用   

這裡利用Hibernate操作資料庫完畢簡單的CRUD操作。

首先。我們須要先寫一個javabean:

package cn.itcast.domain;import java.util.Date;public class User {private int id;private String name;private Date birthday;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}
然後呢。寫上它的對應檔:User.hbm.xml

<?

xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.itcast.domain"><class name="User"><id name="id"><generator class="native"/> </id><property name="name" unique="true" /><property name="birthday" /></class></hibernate-mapping>


繼續我們須要寫出資料庫的對應檔: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.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/test</property><property name="connection.username">sa</property><property name="connection.password">123456</property><property name="hbm2ddl.auto">update</property><property name="show_sql">true</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><mapping resource="cn/itcast/domain/User.hbm.xml" /></session-factory></hibernate-configuration>


當這些都完畢之後,我們須要的就是編寫Dao層了。

首先,我們得實現Dao層的介面(interface):UserDao.java

package cn.itcast.dao;import cn.itcast.domain.User;public interface UserDao {public void saveUser(User user);public User findUserByName(String name);public User findUserById(int id);public void updateUser(User user);public void remove(User user);}


而且我們須要寫一個簡單的HinbernateUtil類來獲得session:HibernateUtil.java

package cn.itcast.dao;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public final class HibernateUtil {private static SessionFactory sessionFactory;private HibernateUtil(){}static{Configuration cfg = new Configuration();cfg.configure();sessionFactory = cfg.buildSessionFactory();}public static SessionFactory getSessionFactory(){return sessionFactory;}public static Session getSession(){return sessionFactory.openSession();}}
接下來。我們就要寫Dao層的實現了:UserDaoImpl.java

package cn.itcast.dao.impl;import org.hibernate.Criteria;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.criterion.Restrictions;import cn.itcast.dao.HibernateUtil;import cn.itcast.dao.UserDao;import cn.itcast.domain.User;public class UserDaoImpl implements UserDao {@Overridepublic void saveUser(User user) { //儲存一個對象Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();s.save(user);tx.commit();}finally{if(s!=null){s.close();}}}@Overridepublic User findUserByName(String name) { //通過name尋找一個對象Session s = null;try{s = HibernateUtil.getSession();Criteria c = s.createCriteria(User.class);c.add(Restrictions.eq("name", name));User user = (User)c.uniqueResult();//這裡返回的是唯一的return user;}finally{if(s!=null){s.close();}}}@Overridepublic User findUserById(int id) { //通過id尋找一個對象Session s = null;try{s = HibernateUtil.getSession();User user = (User) s.get(User.class, id);return user;}finally{if(s!=null){s.close();}}}@Overridepublic void updateUser(User user) { //更新一個對象Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();s.update(user);tx.commit();}finally{if(s!=null){s.close();}}}@Overridepublic void remove(User user) { //刪除一個對象Session s = null;Transaction tx = null;try{s = HibernateUtil.getSession();tx = s.beginTransaction();s.delete(user);tx.commit();}finally{if(s!=null){s.close();}}}}


最後。我們編寫一個測試類類驗證是否成功:DaoTest.java

package cn.test;import java.util.Date;import cn.itcast.dao.UserDao;import cn.itcast.dao.impl.UserDaoHibernateImpl;import cn.itcast.domain.User;public class DaoTest {/** * @param args */public static void main(String[] args) {UserDao dao = new UserDaoHibernateImpl();User user = new User();user.setName("name");user.setBirthday(new Date());dao.saveUser(user);user.setName("new name");dao.updateUser(user);User u = dao.findUserByName(user.getName());dao.remove(u);}}

【SSH三大架構】Hibernate基礎第五篇:利用Hibernate完畢簡單的CRUD操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.