Hibernate的简单增删改查例子

1.导入相应Hibernate的jar包


2.配置文件

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<!-- <session-factory name="foo"> -->
	<session-factory >
		<!-- 数据库URL -->
		<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
		<!-- 数据库用户 -->
		<property name="connection.username">yw</property>
		<!-- 数据库用户密码 -->
		<property name="connection.password">yw</property>
		<!-- 数据库JDBC驱动oracle.jdbc.driver.OracleDriver -->
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<!-- 每个数据库都有其对应的Dialect以匹配其平台特性 -->
		<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
		<!-- 指定当前session范围和上下文 -->
		<property name="current_session_context_class">thread</property>
		<!-- 是否将运行期生成的SQL输出到日志以供调试 -->
		<!-- <property name="show_sql">true</property> -->
		<property name="show_sql">false</property>
		<!-- 映射文件配置,注意配置文件名必须包含其相对于classpath的全路径 -->
		<mapping resource="com/yw/test01/entity/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>


3.配置文件

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>
	<!-- dynamic-update="true" -->
	<class name="com.yw.test01.bean.User" table=""USER"">
		<id name="id" type="java.lang.Integer">
			<column name="id"></column>
			<generator class="sequence">
				<param name="sequence">SEQ_ID</param>
			</generator>
		</id>

		<property name="name" type="java.lang.String">
			<column name="name" length="50" not-null="true"></column>
		</property>

		<property name="password" type="java.lang.String">
			<column name="password" length="50" not-null="true"></column>
		</property>

		<property name="telephone" type="java.lang.String">
			<column name="telephone" length="15" not-null="true"></column>
		</property>

		<property name="username" type="java.lang.String" update="true">
			<column name="username" length="15" not-null="true"></column>
		</property>

		<property name="isadmin" type="java.lang.String">
			<column name="isadmin" length="2" not-null="true"></column>
		</property>
	</class>


</hibernate-mapping>

4.User.java

package com.yw.test01.bean;

import java.io.Serializable;

public class User implements Serializable
{
    private int id;
    private String name;
    private String password;
    private String telephone;
    private String username;
    private String isadmin;
    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 String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }
    public String getTelephone()
    {
        return telephone;
    }
    public void setTelephone(String telephone)
    {
        this.telephone = telephone;
    }
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getIsadmin()
    {
        return isadmin;
    }
    public void setIsadmin(String isadmin)
    {
        this.isadmin = isadmin;
    }
    
    
    
}

5.UserBiz.java

package com.yw.test01.biz;

import com.yw.test01.bean.User;

public interface UserBiz
{
    public boolean register(User user);
    
    public boolean delete(User user);
    
    public boolean update(User user);
    
    public Object getUser(int id);
    
}

6.UserBizImpl.java

package com.yw.test01.bizimpl;

import com.yw.test01.bean.User;
import com.yw.test01.biz.UserBiz;
import com.yw.test01.dao.UserDao;
import com.yw.test01.impl.UserDaoHibImpl;

public class UserBizImpl implements UserBiz
{
    private UserDao ud = new UserDaoHibImpl();
    
    public Object getUser(int id)
    {
        Object obj = null;
        try
        {
            obj = ud.getUser(id);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return obj;
        
    }
    
    @Override
    public boolean register(User user)
    {
        
        try
        {
            ud.save(user);
            return true;
        }
        catch (Exception e)
        {
            
            e.printStackTrace();
            return false;
        }
        
    }
    
    public boolean update(User user)
    {
        
        try
        {
            ud.update(user);
            return true;
        }
        catch (Exception e)
        {
            
            e.printStackTrace();
            return false;
        }
        
    }
    
    public boolean delete(User user)
    {
        
        try
        {
            ud.delete(user);
            return true;
        }
        catch (Exception e)
        {
            
            e.printStackTrace();
            return false;
        }
        
    }
    
    public static void main(String[] args)
    {
        // User user = new User();
        // user.setId(1);
        // user.setIsadmin("N");
        // user.setName("张三1111");
        // user.setPassword("123456");
        // user.setTelephone("123456789");
        // user.setUsername("zhangsan");
        // new UserBizImpl().register(user);
        // new UserBizImpl().update(user);
        
        UserBizImpl ubi = new UserBizImpl();
        User u = (User)ubi.getUser(8);
        System.out.println("id\tIsadmin\tname\tpassword\ttelephone\tusername");
        System.out.println(u.getId() + "\t" + u.getIsadmin() + "\t" + u.getName() + "\t" + u.getPassword() + "\t" + u.getTelephone() + "\t" + u.getUsername());
        
//        u.setName("张三111");
//        u.setIsadmin("N");
        u.setPassword("111111");
        ubi.update(u);
        User u2 = (User)ubi.getUser(8);
        System.out.println("id\tIsadmin\tname\tpassword\ttelephone\tusername");
        System.out.println(u.getId() + "\t" + u.getIsadmin() + "\t" + u.getName() + "\t" + u.getPassword() + "\t" + u.getTelephone() + "\t" + u.getUsername());
        
    }
    
}


7.UserDao.java

package com.yw.test01.dao;

import com.yw.test01.bean.User;

public interface UserDao
{
    
    public void save(User user);
    
    public void update(User user);
    
    public void delete(User user);
    
    public Object getUser(int id);
    
}


8.UserDaoHibImpl.java

package com.yw.test01.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yw.test01.bean.User;
import com.yw.test01.dao.UserDao;
import com.yw.test01.util.BaseHibernateDAO;

public class UserDaoHibImpl extends BaseHibernateDAO implements UserDao
{
    private Session session = null;
    
    public Object getUser(int id)
    {
        Object obj = null;
        Session session = null;
        try
        {
            // 打开session
            session = getSession();
            // 加载数据操作
            // obj=session.get(User.class,id);
            obj = session.get(User.class, id);
        }
        catch (HibernateException e)
        {
            // 回滚事务
            e.printStackTrace();
        }
        finally
        {
            // 关闭session
            session.close();
            
        }
        return obj;
        
    }
    
    public void save(User user)
    {
        Transaction tx = null;
        
        try
        {
            session = getSession();
            // 开始一个事务
            tx = session.beginTransaction();
            // 持久化操作
            session.save(user);
            // 提交事务
            tx.commit();
        }
        catch (HibernateException e)
        {
            // 回滚事务
            tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
        
    }
    
    public void update(User user)
    {
        Transaction tx = null;
        
        try
        {
            session = getSession();
            // 开始一个事务
            tx = session.beginTransaction();
            // 持久化操作
            session.update(user);
            // 提交事务
            tx.commit();
        }
        catch (HibernateException e)
        {
            // 回滚事务
            tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
        
    }
    
    public void delete(User user)
    {
        Transaction tx = null;
        
        try
        {
            session = getSession();
            // 开始一个事务
            tx = session.beginTransaction();
            // 持久化操作
            session.delete(user);
            // 提交事务
            tx.commit();
        }
        catch (HibernateException e)
        {
            // 回滚事务
            tx.rollback();
            e.printStackTrace();
        }
        finally
        {
            session.close();
        }
        
    }
    
}


9.BaseHibernateDao.java

package com.yw.test01.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class BaseHibernateDAO
{
    
    // static SessionFactory sf = new Configuration().configure()
    // .buildSessionFactory();
    // static Session session = sf.openSession();
    // Transaction tx = session.beginTransaction();
    // openSession()每一次都产生一个新的session
    
    private static Configuration configuration;
    
    private static SessionFactory sessionFactory;
    
    static
    {
        configuration = new Configuration();
        // 读取配置文件
        configuration.configure();
        // 创建SessionFactory
        sessionFactory = configuration.buildSessionFactory();
        
    }
    
    public static Configuration getConfiguration()
    {
        return configuration;
    }
    
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
    
    public static Session getSession()
    {
        // 打开session//sf.openSession();
        //return getSessionFactory().getCurrentSession();
        // return session;
        return getSessionFactory().openSession();
    }
    
}


10.Oracle 10g数据库表USER



CREATE  SEQUENCE SEQ_ID
INCREMENT 
BY   1   --  每次加几个
START  WITH   1   --  从1开始计数
NOMAXvalue  --  不设置最大值
NOCYCLE  --  一直累加,不循环
CACHE  10 -- 设置缓存cache个序列,如果系统down掉了或者其它情况将会导致序列不连续,也可以设置为---------NOCACHE



运行结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值