认真去做一件事,总会有所收获的

使用hibernate如何进行数据持久化,

在这里我首先需要的是把各个pojo的数据进行xml配置,如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?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.lxh.entity.Manager" table="manager" catalog="bbs">
<id name="managerId" type="java.lang.Integer">
<column name="managerId" />
<generator class="native" />
</id>
<property name="managerName" type="java.lang.String">
<column name="managerName" length="16" not-null="true" />
</property>
<property name="managerPassword" type="java.lang.String">
<column name="managerPassword" length="12" not-null="true" />
</property>
</class>
</hibernate-mapping>
```
需要给出数据库名字和表,然后由hibernate进行数据的转换,确定对应的关系,封装了数据然后传递给数据库进行交互,然后就是配置该个数据的连接数据,在之中配置账号和密码等信息,现在市面有很多的数据封装,druid和c3po就是对数据进行了封装。在数据传输会有办法进行对数据库的加密,这个下一个方面会提到,这里给出对数据的配置
```java
<?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">
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/bbs
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<mapping resource="com/lxh/entity/Manager.hbm.xml" />
<mapping resource="com/lxh/entity/Question.hbm.xml" />
<mapping resource="com/lxh/entity/User.hbm.xml" />
</session-factory>
</hibernate-configuration>

在这里配置了数据驱动和账号密码等信息。然后接下来就是对数据进行封装和持久化,这样就有下面的配置,这是使用了SessionFactory和configuration对配置文件进行读取,然后就是对dao的配置和使用啦,这里要提到的是在这个过程中可以使用加密算法的使用,这里我也找了一个加密的算法进行简单的书写,号直接来看过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.lxh.dao;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.lxh.config.HibernateSessionFactory;
import com.lxh.entity.Manager;
import com.lxh.entity.Question;
import com.lxh.entity.User;
@SuppressWarnings("deprecation")
public class ManagerDaoImpl extends UserDaoImpl implements ManagerDao {
private Session session;
private Query query;
private Transaction transaction;
@SuppressWarnings("unchecked")
@Override
public Manager judgeManager(Manager manager) {
Manager manager2 = null;
session = HibernateSessionFactory.getSession();
String hql = "from Manager as manager where manager.managerName = ? and manager.managerPassword = ?";
query = session.createQuery(hql);
query.setString(0, manager.getManagerName());
query.setString(1, manager.getManagerPassword());
Iterator<Manager> iterator = query.list().iterator();
if(iterator.hasNext()){
manager2 = iterator.next();
}
session.close();
return manager2;
}
@Override
public void saveManager(Manager manager) {
session=HibernateSessionFactory.getSession();
transaction=session.beginTransaction();
session.save(manager);
transaction.commit();
session.close();
}
@Override
public int QuestionAmount() {
int questionAmount = 0;
session = HibernateSessionFactory.getSession();
String hql = "select count(*) from Question";
query = session.createQuery(hql);
long l = (Long)query.uniqueResult();
questionAmount = (int)l;
session.close();
return questionAmount;
}
@SuppressWarnings("unchecked")
@Override
public List<Question> allQuestion(int pageNumber, int pageSize) {
session = HibernateSessionFactory.getSession();
List<Question> allQuestion = new ArrayList<Question>();
String hql = "from Question as question order by question.postTime desc";
query = session.createQuery(hql);
query.setFirstResult((pageNumber - 1)*pageSize);
query.setMaxResults(pageSize);
allQuestion = query.list();
session.close();
return allQuestion;
}
@Override
public User findUser(int userId) {
session=HibernateSessionFactory.getSession();
User user=(User)session.get("com.lxh.entity.User", userId);
session.close();
return user;
}
@Override
public void deleteQuestion(Question question) {
session = HibernateSessionFactory.getSession();
transaction = session.beginTransaction();
session.delete(question);
transaction.commit();
session.close();
}
/**分页,返回当前页数和总页数*/
public int[] pageNumber(int questionAmount,String pageNumberStr,int pageSize){
int[] paging = new int[2];
int pageNumber = 1;
pageNumber = Integer.parseInt(pageNumberStr);
if(pageNumber <= 0){
pageNumber = 1;
}
int totalPage = 1;
if(questionAmount > 0){
totalPage = questionAmount%pageSize==0?(questionAmount/pageSize):(questionAmount/pageSize+1);
}
if(pageNumber > totalPage){
pageNumber = totalPage;
}
paging[0] = pageNumber;
paging[1] = totalPage;
return paging;
}
}

当然在一个显示的过程中,分页的操作是必不可少的,这样简单的数据持久层就已经完成了,不过还需要一些其他的完善,这个你写一个demo慢慢去体会。这就是我搭建的一个论坛的一些简单的持久化代码,这也是最近几天特训老师说的一些知识,希望对你有帮助吧。

加密工具类

加密是表单查询必不可少的,这个是从github上看到的,侵权必删,下面就是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.vote.service;
import java.security.MessageDigest;
public class MD5Util {
/**
* 密码加密
* @param inStr
* @return
* @throws Exception
*/
public static String MD5Encrypt(String inStr) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5"); // 可以选中其他的算法如SHA
byte[] digest = md.digest(inStr.getBytes()); // 返回的是byet[],要转化为String存储比较方便
String outStr = byteToString(digest);
return outStr;
}
/**
* byteToString
* @param digest
* @return
* @throws Exception
*/
private static String byteToString(byte[] digest) throws Exception {
String str = "";
String tempStr = "";
StringBuffer sb = new StringBuffer("");
for (int i = 1; i < digest.length; i++) {
tempStr = (Integer.toHexString(digest[i] & 0xff));
if (tempStr.length() == 1) {
sb.append("0");
sb.append(tempStr);
} else {
sb.append(tempStr);
}
}
str = sb.toString().toUpperCase();
return str;
}
}

总结

在这里确实学到很多在学校里学不到的东西,不过这里的环境就不说啦,总之自己考量,在这里让我考虑和认识了另一个社会和自己。

文章目录
  1. 1. 使用hibernate如何进行数据持久化,
    1. 1.1. 加密工具类
    2. 1.2. 总结
,