hibernate基本操作

1.准备条件:
1.1 创建hibernate2工程
1.2 导入hibernate包
1.3 创建hibernate2数据库,以及customers表
2. Customers.java

package com.hibernate2.bean;

import java.sql.Date;
import java.sql.Timestamp;

public class Customers {
private Long id;
private String name;
private String email;
private String password;
private Integer phone;
private String address;
private char sex;
private boolean is_married;
private String description;
private byte[] image;
private Date birthday;
private Timestamp registered_time;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getPhone() {
return phone;
}
public void setPhone(Integer phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public boolean isIs_married() {
return is_married;
}
public void setIs_married(boolean isMarried) {
is_married = isMarried;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Timestamp getRegistered_time() {
return registered_time;
}
public void setRegistered_time(Timestamp registeredTime) {
registered_time = registeredTime;
}

}

3. 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">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

<session-factory>
<!--
<property name="format_sql">true</property>
-->
<property name="show_sql">true</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate2</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<mapping resource="customers.hbm.xml" />
</session-factory>

</hibernate-configuration>

4.customers.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>
<class name="com.hibernate2.bean.Customers" table="customers">
<id name="id" column="id" type="long">
<generator class="increment"></generator>
</id>
<property name="name" column="name" type="string"></property>
<property name="email" column="email" type="string"></property>
<property name="password" column="password" type="string"></property>
<property name="phone" column="phone" type="integer"></property>
<property name="address" column="address" type="string"></property>
<property name="sex" column="sex" type="char"></property>
<property name="is_married" column="is_married" type="boolean"></property>
<property name="description" column="description" type="text"></property>
<property name="image" column="image" type="binary"></property>
<property name="birthday" column="birthday" type="date"></property>
<property name="registered_time" column="registered_time" type="timestamp"></property>
</class>
</hibernate-mapping>

5. HibernateTest.java

package com.hibernate2.bean;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

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

public class HibernateTest {

private static SessionFactory sessionFactory;

static{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}catch(Exception ex){
System.out.println("创建sessionFactory时出错");
}
}

private void saveCustomer(Customers cust){
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
session.save(cust);
tx.commit();
}catch(Exception ex){
System.out.println("保存数据时出错");
if(tx!=null){
tx.rollback();
}
}finally{
session.close();
}

}

@SuppressWarnings("unchecked")
private void findAllCustomer(PrintStream out){
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
String hql="from Customers as c order by c.name asc";
Query query=session.createQuery(hql);
List custs=query.list();
for(Iterator it=custs.iterator();it.hasNext();){
printCustomer((Customers)it.next(), out);
}
tx.commit();
}catch(Exception ex){
System.out.println("保存数据时出错");
if(tx!=null){
tx.rollback();
}
}finally{
session.close();
}
}

private void loadAndUpdateCustoemr(Long id,String address){
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
Customers cust=(Customers)session.load(Customers.class, id);
cust.setAddress(address);
tx.commit();
}catch(Exception ex){
System.out.println("保存数据时出错");
if(tx!=null){
tx.rollback();
}
}finally{
session.close();
}
}

@SuppressWarnings("unchecked")
private void deleteCutomer(Customers cust){
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
List custs=session.createQuery("from Customers").list();
for(Iterator it=custs.iterator();it.hasNext();){
session.delete(it.next());
}
tx.commit();
}catch(Exception ex){
System.out.println("保存数据时出错");
if(tx!=null){
tx.rollback();
}
}finally{
session.close();
}
}

private void printCustomer(Customers cust,PrintStream out) throws Exception{
OutputStream output=new FileOutputStream("new_photo.gif");
byte[] buffer=cust.getImage();
output.write(buffer);

out.println("--------------以下是"+cust.getName()+"的信息-----------------------");
out.println("ID:"+cust.getId());
out.println("name:"+cust.getName());
out.println("email:"+cust.getEmail());
out.println("password:"+cust.getPassword());
out.println("phone:"+cust.getPhone());
out.println("address:"+cust.getAddress());
out.println("sex:"+cust.getSex());
String married=cust.isIs_married()==true?"已婚":"未婚";
out.println("is_married:"+married);
out.println("description:"+cust.getDescription());
out.println("birthday:"+cust.getBirthday());
out.println("registered_time:"+cust.getRegistered_time());

}

private void test(PrintStream out) throws Exception{
Customers customer=new Customers();
customer.setName("zs");
customer.setEmail("zs@163.com");
customer.setPassword("123");
customer.setPhone(123456789);
customer.setAddress("a new address");
customer.setSex('男');
customer.setIs_married(true);
customer.setDescription("a new description");
InputStream in=this.getClass().getResourceAsStream("photo.gif");
byte[] buffer=new byte[in.available()];
in.read(buffer);
customer.setImage(buffer);
customer.setBirthday(Date.valueOf("1980-1-1"));

saveCustomer(customer);

// findAllCustomer(out);

loadAndUpdateCustoemr(customer.getId(), "update address");

// deleteCutomer(customer);

}

public static void main(String[] args) throws Exception{
new HibernateTest().test(System.out);
sessionFactory.close();
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值