Hibernate主要是在开发中对Dao(database access object)层进行操作,因为他主要是操作数据库的,所以hibernate主要用于数据库的增删查改,下面就来一一介绍:
1.配置hibernate,在src目录下新建一个名为hibernate.cfg.xml的文件,然后在里面做第一步的配置,在下面的配置中,基本上很直观的知道意思,但是current_session_context_class
这个配置需要解释一下,本身hibernate工厂是一个单例,所以无论是哪一个地方的请求,调用的都是同一个对象,但是如果加上
<property name="hibernate.current_session_context_class">thread</property>
的话,对于每个IP地址,会有一个自己的本地对象。
<?xml version="1.0" encoding="UTF-8"?>
<!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">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///xxh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="com/xiaoxiaohei/entity/User.hbm.xml"/>
<mapping resource="com/xiaoxiaohei/entity/Customer.hbm.xml"/>
<mapping resource="com/xiaoxiaohei/entity/LinkMan.hbm.xml"/>
<mapping resource="com/xiaoxiaohei/entity/Users.hbm.xml"/>
<mapping resource="com/xiaoxiaohei/entity/Role.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2.第二部创建实体类,一般这个包我们命名为entity。实体类中分为3中关系,1对1,1对多,多对多:
a.一对一关系配置
首先定义实体类,这里需要注意的是,基本类型建议用包装类的定义,下面是一个例子
public class User {
private Integer uid;
// private String uid;
private String username;
private String password;
private String address;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", address=" + address + "]";
}
}
然后创建这个类的配置文件User.hbm.xml
,一般主键用native:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 配置类和表 -->
<class name="com.xiaoxiaohei.entity.User" table="user">
<id name="uid" column="uid">
<!-- <generator class="uuid"></generator> -->
<generator class="native"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
<property name="address" column="address"></property>
</class>
</hibernate-mapping>
b.一对多关系配置,注意一方对应的类要有多方的Set集合,多方对应的类要有一方的对象。还有配置文件中的many-to-one和one-to-many
public class LinkMan {
private Integer lkm_id;
private String lkm_name;
private String lkm_gender;
private String lkm_phone;
private Customer customer;
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Integer getLkm_id() {
return lkm_id;
}
public void setLkm_id(Integer lkm_id) {
this.lkm_id = lkm_id;
}
public String getLkm_name() {
return lkm_name;
}
public void setLkm_name(String lkm_name) {
this.lkm_name = lkm_name;
}
public String getLkm_gender() {
return lkm_gender;
}
public void setLkm_gender(String lkm_gender) {
this.lkm_gender = lkm_gender;
}
public String getLkm_phone() {
return lkm_phone;
}
public void setLkm_phone(String lkm_phone) {
this.lkm_phone = lkm_phone;
}
@Override
public String toString() {
return "LinkMan [lkm_id=" + lkm_id + ", lkm_name=" + lkm_name + ", lkm_gender=" + lkm_gender + ", lkm_phone="
+ lkm_phone + ", customer=" + customer + "]";
}
}
import java.util.HashSet;
import java.util.Set;
public class Customer {
private Integer cid;
private String custName;
private String custLevel;
private String custSource;
private String custPhone;
private String custMobile;
private Set<LinkMan> setLinkMan = new HashSet<>();
public Set<LinkMan> getSetLinkMan() {
return setLinkMan;
}
public void setSetLinkMan(Set<LinkMan> setLinkMan) {
this.setLinkMan = setLinkMan;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public String getCustSource() {
return custSource;
}
public void setCustSource(String custSource) {
this.custSource = custSource;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
public String getCustMobile() {
return custMobile;
}
public void setCustMobile(String custMobile) {
this.custMobile = custMobile;
}
@Override
public String toString() {
return "Customer [cid=" + cid + ", custName=" + custName + ", custLevel=" + custLevel + ", custSource="
+ custSource + ", custPhone=" + custPhone + ", custMobile=" + custMobile + "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 配置类和表 -->
<class name="com.xiaoxiaohei.entity.Customer" table="customer">
<id name="cid" column="cid">
<generator class="native"></generator>
</id>
<property name="custName" column="custName"></property>
<property name="custLevel" column="custLevel"></property>
<property name="custSource" column="custSource"></property>
<property name="custPhone" column="custPhone"></property>
<property name="custMobile" column="custMobile"></property>
<set name="setLinkMan" cascade="save-update,delete" inverse="true" fetch="select" lazy="extra" batch-size="2">
<key column="clid"></key>
<one-to-many class="com.xiaoxiaohei.entity.LinkMan" />
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 配置类和表 -->
<class name="com.xiaoxiaohei.entity.LinkMan" table="link_man">
<id name="lkm_id" column="lkm_id">
<!-- <generator class="uuid"></generator> -->
<generator class="native"></generator>
</id>
<property name="lkm_name" column="lkm_name"></property>
<property name="lkm_gender" column="lkm_gender"></property>
<property name="lkm_phone" column="lkm_phone"></property>
<many-to-one name="customer" class="com.xiaoxiaohei.entity.Customer" column="clid"></many-to-one>
</class>
</hibernate-mapping>
c.多对多关系的配置
import java.util.HashSet;
import java.util.Set;
import java.util.HashSet;
import java.util.Set;
public class Role {
private Integer role_id;
private String role_name;
private String role_memo;
private Set<Users> setUser = new HashSet<>();
public Set<Users> getSetUser() {
return setUser;
}
public void setSetUser(Set<Users> setUser) {
this.setUser = setUser;
}
public Integer getRole_id() {
return role_id;
}
public void setRole_id(Integer role_id) {
this.role_id = role_id;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getRole_memo() {
return role_memo;
}
public void setRole_memo(String role_memo) {
this.role_memo = role_memo;
}
}
public class Users {
private Integer user_id;
private String user_name;
private String user_password;
private Set<Role> setRole = new HashSet<>();
public Set<Role> getSetRole() {
return setRole;
}
public void setSetRole(Set<Role> setRole) {
this.setRole = setRole;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 配置类和表 -->
<class name="com.xiaoxiaohei.entity.Role" table="role">
<id name="role_id" column="role_id">
<!-- <generator class="uuid"></generator> -->
<generator class="native"></generator>
</id>
<property name="role_name" column="role_name"></property>
<property name="role_memo" column="role_memo"></property>
<set name="setUser" table="user_role">
<key column="roleid"></key>
<many-to-many class="com.xiaoxiaohei.entity.Users" column="userid"></many-to-many>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 配置类和表 -->
<class name="com.xiaoxiaohei.entity.Users" table="users">
<id name="user_id" column="user_id">
<!-- <generator class="uuid"></generator> -->
<generator class="native"></generator>
</id>
<property name="user_name" column="user_name"></property>
<property name="user_password" column="user_password"></property>
<set name="setRole" table="user_role" cascade="save-update,delete">
<key column="userid"></key>
<many-to-many class="com.xiaoxiaohei.entity.Role" column="roleid"></many-to-many>
</set>
</class>
</hibernate-mapping>
对于hibernate的使用,一般我们会封装一个工厂类来实现操作
public class HibernateUtils {
private static Configuration cfg = null;
private static SessionFactory sessionFactory = null;
static {
cfg = new Configuration();
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSessionObject() {
return sessionFactory.getCurrentSession();
}
public static void main(String[] args) {
}
}
下面给出demo
1.demo1
public class Demo1 {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
// user.setUid(5);
user.setUsername("8888888");
user.setPassword("123456");
user.setAddress("锟秸憋拷");
session.save(user);
/*session.saveOrUpdate(user);
System.out.println(user.getUid());*/
// User user1 = session.get(User.class, 5);
/*System.out.println(user1);
User user2 = session.get(User.class, 5);
System.out.println(user2);
System.out.println(user1==user2);*/
// user1.setUsername("bbbbbbb");
tx.commit();
session.close();
sessionFactory.close();
}
}
2.demo2
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.xiaoxiaohei.entity.User;
import com.xiaoxiaohei.util.HibernateUtils;
public class Demo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
Session session = sessionFactory.openSession();*/
Session session = HibernateUtils.getSessionObject();
Transaction tx = session.beginTransaction();
// User user = session.get(User.class, 2);
// user.setUsername("uuuuu");
// session.update(user);
// session.save(user);
// session.delete(user);
User user = new User();
user.setUid(4);
session.delete(user);
tx.commit();
System.out.println(user);
session.close();
}
}
3.demo3
public class Demo3 {
public static void main(String[] args) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
sessionFactory = HibernateUtils.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
User user = new User();
user.setUsername("iiiiii");
user.setPassword("1111111");
user.setAddress("oooooooo");
session.save(user);
tx.commit();
} catch(Exception e) {
tx.rollback();
} finally {
session.close();
sessionFactory.close();
}
}
}
4.demo4
public class Demo4 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Query query = session.createQuery("from User");//注意大小写,小写不行
List<User> list = query.list();
for(User u : list) {
System.out.println(u);
}
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
5.demo5
public class Demo5 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(User.class);
List<User> list = criteria.list();
for(User u : list) {
System.out.println(u);
}
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
6.demo6
public class Demo6 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Customer customer = new Customer();
customer.setCustName("aaaa");
customer.setCustLevel("vip");
customer.setCustSource("oooo");
customer.setCustPhone("2222222");
customer.setCustMobile("999999");
LinkMan linkMan = new LinkMan();
linkMan.setLkm_name("uuuuu");
linkMan.setLkm_gender("nan");
linkMan.setLkm_phone("ppp");
customer.getSetLinkMan().add(linkMan);
customer.getSetLinkMan().add(linkMan);
// linkMan.setCustomer(customer);
session.save(customer);
// session.save(linkMan);
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
7.demo7
public class Demo7 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Customer customer = session.get(Customer.class, 1);
session.delete(customer);
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
8.demo8
public class Demo8 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Customer baidu = session.get(Customer.class, 3);
LinkMan lucy = session.get(LinkMan.class, 3);
baidu.getSetLinkMan().add(lucy);
lucy.setCustomer(baidu);
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
9.demo9
public class Demo9 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Users users1 = new Users();
users1.setUser_name("xxxxxx");
users1.setUser_password("pppppp");
Users users2 = new Users();
users2.setUser_name("2222222");
users2.setUser_password("222222");
Role role1 = new Role();
role1.setRole_name("rrrrrr");
role1.setRole_memo("mmmmmmm");
Role role2 = new Role();
role2.setRole_name("22222");
role2.setRole_memo("222222");
Role role3 = new Role();
role3.setRole_name("333333");
role3.setRole_memo("3333333");
users1.getSetRole().add(role1);
users1.getSetRole().add(role2);
users2.getSetRole().add(role2);
users2.getSetRole().add(role3);
session.save(users1);
session.save(users2);
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
10.demo10
public class Demo10 {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSessionObject();
tx = session.beginTransaction();
Users users = session.get(Users.class, 1);
session.delete(users);
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
}
}
}
11.demo11
public class Demo11 {
public static void main(String[] args) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
sessionFactory = HibernateUtils.getSessionFactory();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
Customer customer = session.get(Customer.class, 2);
Set<LinkMan> set = customer.getSetLinkMan();
for(LinkMan man : set) {
System.out.println(man);
}
tx.commit();
} catch(Exception e) {
tx.rollback();
} finally {
session.close();
}
}
}
12.demo12
public class Demo12 {
public static void main(String[] args) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
sessionFactory = HibernateUtils.getSessionFactory();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
/*Query<Customer> query = session.createQuery("from Customer", Customer.class);
List<Customer> list = query.getResultList();
System.out.println(list);
for(Customer c : list) {
System.err.println(c);
}*/
/*for(int i = 0; i < 50; i++) {
Customer c = new Customer();
c.setCustName("name---"+i);
session.save(c);
}*/
Query<Customer> query = session.createQuery("from Customer order by cid desc", Customer.class);
query.setFirstResult(0);
query.setMaxResults(10);
List<Customer> list = query.getResultList();
for(Customer c : list) {
System.err.println(c);
}
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
session.close();
}
}
}
13.demo13
public class Demo13 {
public static void main(String[] args) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
sessionFactory = HibernateUtils.getSessionFactory();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
// Criteria criteria = session.createCriteria(Customer.class);
// criteria.add(Restrictions.eq("cid", 42));
/*criteria.addOrder(Order.desc("cid"));
criteria.setFirstResult(0);
criteria.setMaxResults(5);
List<Customer> list = criteria.list();
for(Customer c : list) {
System.out.println(c);
}*/
/*criteria.setProjection(Projections.rowCount());
Object obj = criteria.uniqueResult();
Long lobj = (Long) obj;
System.out.println(lobj.intValue());*/
/*Query query = session.createQuery("from Customer c inner join c.setLinkMan");
List<Object[]> list = query.list();
for(Object[] obj : list) {
System.out.println(obj[0]);
System.out.println(obj[1]);
}*/
Query query = session.createQuery("from Customer c inner join fetch c.setLinkMan");
List list = query.list();
System.out.println(list);
tx.commit();
} catch(Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
session.close();
}
}
}