最近开始狂看Hibernate,发觉很有看头,要彻底了解其运作还是需要一定时日。
记录最简单的操作吧
数据库
CREATE TABLE manager (
id integer primary key DEFAULT nextval('serial'::text) NOT NULL,
name character varying(20) NOT NULL,
"password" character varying(20)
);
map文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
<class name="Manager" table="manager">
<id name="id" type="java.lang.Integer" column="id">
<generator class="sequence">
<param name="sequence">manager_id_serial</param>
</generator>
</id>
<property
name="name"
type="java.lang.String"
column="name"
length="20"
>
<meta attribute="scope-get">private</meta>
<meta attribute="scope-set">private</meta>
<meta attribute="beans-property-type">constrained</meta>
</property>
<property
name="password"
type="java.lang.String"
column="password"
length="20"
/>
</class>
</hibernate-mapping>
插入数据
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class InsertData {
public static void main(String[] args) {
try {
SessionFactory sf =
new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
for (int i = 1; i < 10; i++) {
Manager m = new Manager();
m.setName("Name" + i);
m.setPassword("Password");
session.save(m);
}
tx.commit();
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
更新数据
public class UpdateData {
/*
delete data
*/
public static void main(String[] args) {
try {
SessionFactory sf =
new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
//String m = "Name0";
Manager m1 = new Manager();
m1.setId(1);
m1.setName("lanhuizi");
m1.setPassword("Nothing");
session.update(m1);
tx.commit();
session.close();
} catch (HibernateException e) {
System.out.println("error");
}
}
}
删除数据
public class DeleteData {
/*
delete data
*/
public static void main(String[] args) {
try {
SessionFactory sf =
new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
//String m = "Name0";
Manager m1 = new Manager();
m1.setId(1);
session.delete(m1);
tx.commit();
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
以上只是简单的操作,应该有更好的实现方法,批量删除,批量更新尤其是这样。
路漫漫啊
本文地址:http://com.8s8s.com/it/it14168.htm