首页 > 其他分享 >Hibernate学习总结

Hibernate学习总结

时间:2022-11-24 17:31:50浏览次数:45  
标签:总结 Hibernate String tx void 学习 session user public


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();
}
}
}


标签:总结,Hibernate,String,tx,void,学习,session,user,public
From: https://blog.51cto.com/u_15890522/5884401

相关文章

  • K8S学习记录
    kubelet在启动之后会一直闪烁运行;systemctlstatuskubelet之后,会发现有时候runnning有时候退出,属于一直闪烁。(尚硅谷P34视频最后)systemctl命令 ctl表示controller。......
  • android学习布局管理器的一些心得——基础篇
    LinearLayout---线性布局   在LinearLayout中,如下方法是比较容易忘记的,而且这些方法是LinearLayout常用的方法:1.android:gravity(在代码编程实现中的方法为:setGravit......
  • android学习布局管理器的一些心得2——基础篇
    RelativeLayout-----相对布局1.RelativeLayout不是相对于单体的布局,每一个组件的布局都要依赖另外一个或多个组件,这个布局表示的是一个组件相对于另一个组件(或者是整个Rel......
  • 如何为机器学习进行数据标签、版本控制和管理
    一个丰富食物数据集的案例研究介绍几个月前,托洛卡和ClearML公司一起创建了此联合项目。我们的目标是向其他机器学习的从业者展示从收集数据到将数据输入机器学习模型之......
  • linux学习用到的命令
    创建快件方式ln创建目录的快件方式sudoln-s/root/myhack//root/Desktop以上指令是创建软链接到桌面。ln-s/mnt/hgfs/VMware_share//home/ICer/Vm_Share指令......
  • Vue学习笔记(2)
    31.父子组件通信1.父亲给儿子通信利用props2.儿子给父亲通信,先利用props让父亲给儿子传个函数,再让儿子再调用函数32.todolist案例总结组件化编码流程:(1).拆分静态组......
  • 【Win32 API学习】模拟键盘输入和鼠标输入
    在Windows大行其道的今天,windows界面程序受到广大用户的欢迎。对这些程序的操作不外乎两种,键盘输入控制和鼠标输入控制。有时,对于繁杂的,或重复性的输入操作,我们能否通过编......
  • 【go】go微服务框架kratos学习笔记十(熔断器)
    什么是熔断假设存在这样的调用链:服务A->服务B->服务C如果服Ccrash或者一些原因导致不可用,服B可能会阻塞很多线程/协程,如果短时间内大量积压,导致系统资源耗尽服B......
  • 西门子PLC指令学习新想法随笔
    1,上升下降沿的用法:(用来记录运动中的物品数据,变化中的信息数据)(1),与set和rst配合,记录报警信息,放置用线圈记录时,报警信息同步消失;(2),与光电开关配合用于输送线体上的物品计数,一......
  • 【Cocos2dx通信(Http&Socket)相关编译到Android细节总结】编译加入curl关联lib与头文
    本站文章均为​​ 李华明Himi ​​​原创,转载务必在明显处注明:​​​​​本篇介绍在Cocos2dx中加入网络通信相关代码,然后编译到Android时出现的一些细节和需要注意的地方......