郵件伺服器MailServer之 Hibernate持久層開發
第一步:資料庫設計
- MailServer物理模型圖
- 表鍵的清單
名稱 | 程式碼 |
使用者暱稱 | nick_name |
郵箱地址 | mail_address |
使用者密碼 | user_password |
我的郵箱 | mail_address |
好友郵箱 | friend_address |
好友備註 | remark_name |
郵件編號 | mail_id |
接收郵箱 | mail_receive |
傳送時間 | send_time |
郵件主題 | mail_subject |
郵件正文 | mail_content |
傳送狀態 | state_send |
讀取狀態 | state_read |
正文編碼 | content_encoding |
協議版本 | protocol_version |
定時傳送 | timing |
郵件編號 | mail_id |
附件編號 | adjunct_id |
附件格式 | adjunct_type |
附件大小 | adjunct_size |
附件路徑 | adjunct_url |
帳號 | account |
密碼 | password |
- 資料庫指令碼(先建立資料庫再執行指令碼)
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50720
Source Host : localhost:3306
Source Database : mail_server
Target Server Type : MYSQL
Target Server Version : 50720
File Encoding : 65001
Date: 2018-03-31 13:39:54
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for address_book
-- ----------------------------
DROP TABLE IF EXISTS `address_book`;
CREATE TABLE `address_book` (
`mail_address` varchar(25) NOT NULL COMMENT '我的郵件地址',
`friend_address` varchar(25) NOT NULL COMMENT '好友郵件地址',
`remark_name` varchar(25) DEFAULT NULL COMMENT '好友備註',
PRIMARY KEY (`mail_address`,`friend_address`),
CONSTRAINT `FK_Reference_1` FOREIGN KEY (`mail_address`) REFERENCES `user_entity` (`mail_address`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='通訊錄';
-- ----------------------------
-- Records of address_book
-- ----------------------------
-- ----------------------------
-- Table structure for adjunct
-- ----------------------------
DROP TABLE IF EXISTS `adjunct`;
CREATE TABLE `adjunct` (
`mail_id` varchar(25) NOT NULL COMMENT '郵件ID',
`adjunct_id` varchar(25) NOT NULL COMMENT '附件ID',
`adjunct_type` varchar(5) DEFAULT NULL COMMENT '附件格式',
`adjunct_size` double NOT NULL COMMENT '附件大小',
`adjunct_url` varchar(100) NOT NULL COMMENT '附件地址',
PRIMARY KEY (`adjunct_id`),
KEY `FK_Reference_3` (`mail_id`),
CONSTRAINT `FK_Reference_3` FOREIGN KEY (`mail_id`) REFERENCES `mail_entity` (`mail_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='附件表';
-- ----------------------------
-- Records of adjunct
-- ----------------------------
-- ----------------------------
-- Table structure for admin
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`account` varchar(25) NOT NULL COMMENT '管理員帳號',
`password` varchar(25) NOT NULL COMMENT '管理員密碼',
PRIMARY KEY (`account`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='管理員';
-- ----------------------------
-- Records of admin
-- ----------------------------
-- ----------------------------
-- Table structure for mail_entity
-- ----------------------------
DROP TABLE IF EXISTS `mail_entity`;
CREATE TABLE `mail_entity` (
`mail_id` varchar(25) NOT NULL COMMENT '郵件編號',
`mail_address` varchar(25) NOT NULL COMMENT '傳送方郵箱',
`mail_receive` varchar(25) NOT NULL COMMENT '接收方郵箱',
`send_time` datetime NOT NULL COMMENT '傳送時間',
`mail_subject` varchar(50) NOT NULL COMMENT '郵件主題',
`mail_content` varchar(2048) NOT NULL COMMENT '郵件正文',
`state_send` varchar(4) NOT NULL COMMENT '傳送方郵件狀態',
`state_read` varchar(2) DEFAULT NULL COMMENT '接收方郵件狀態',
`content_encoding` varchar(10) DEFAULT NULL COMMENT '郵件正文編碼',
`protocol_version` varchar(10) DEFAULT NULL COMMENT '郵件協議版本',
`timing` datetime DEFAULT NULL COMMENT '定時傳送時間',
PRIMARY KEY (`mail_id`),
KEY `FK_Reference_2` (`mail_address`),
CONSTRAINT `FK_Reference_2` FOREIGN KEY (`mail_address`) REFERENCES `user_entity` (`mail_address`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='郵件';
-- ----------------------------
-- Records of mail_entity
-- ----------------------------
-- ----------------------------
-- Table structure for user_entity
-- ----------------------------
DROP TABLE IF EXISTS `user_entity`;
CREATE TABLE `user_entity` (
`nick_name` varchar(25) NOT NULL COMMENT '使用者暱稱',
`mail_address` varchar(25) NOT NULL COMMENT '郵箱地址',
`user_password` varchar(15) NOT NULL COMMENT '使用者密碼',
PRIMARY KEY (`mail_address`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='使用者';
-- ----------------------------
-- Records of user_entity
-- ----------------------------
INSERT INTO `user_entity` VALUES ('佚陽', ' [email protected]', '1557644');
INSERT INTO `user_entity` VALUES ('佚陽', '[email protected]', '1557644');
INSERT INTO `user_entity` VALUES ('佚陽', '[email protected]', '123456');
INSERT INTO `user_entity` VALUES ('信仰', '[email protected]', '123456');
第二步:在Eclipse新建Java工程並搭建Hibernate開發環境
-下載Hibernate依賴包以及最新版MySQL的JDBC驅動
-解壓hibernate-release-5.2.16.Final以及mysql-connector-java-5.1.46
-在專案下新建資料夾(lib)
-複製hibernate-release-5.2.16.Final\lib\required下的所有包以及
hibernate-release-5.2.16.Final\lib\jpa-metamodel-generator下的包以及
mysql-connector-java-5.1.46\mysql-connector-java-5.1.46-bin.jar
貼上至lib目錄,選中匯入的所有包,右鍵BulidPath
-至此,Hibernate開發環境就搭建好啦
第三步:配置Hibernate資料庫連線和表對映並編寫業務實現類
-在src目錄下右鍵新建File,命名為hibernate.cfg.xml,這是Hibernate的資料庫連線配置檔案,在檔案裡寫入如下程式碼:
<?xml version="1.0" encoding="UTF-8"?>
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License:
GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the
lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!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://localhost:3306/mail_server</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">****</property><!-- 請自行配置資料庫連線-->
<!-- connection.pool_size:配置JDBC連線池 -->
<property name="connection.pool_size">20</property>
<!-- dialect:配置資料庫方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- show_sql:操作資料庫時,會向控制檯列印sql語句 -->
<property name="show_sql">true</property>
<!-- format_sql:列印sql語句前,會將sql先格式化 -->
<!-- <property name="format_sql">true</property> -->
<!-- hbm2ddl.auto:是否自動生成表結構 -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<!-- 列出所有對映檔案 -->
<mapping resource="com/belief/model/User.hbm.xml" />
<mapping resource="com/belief/model/Mail.hbm.xml" />
<mapping resource="com/belief/model/Admin.hbm.xml" />
<mapping resource="com/belief/model/Adjunct.hbm.xml" />
<mapping resource="com/belief/model/Address.hbm.xml" />
</session-factory>
</hibernate-configuration>
-在src下新建五個包:分別為
com.belief.dao----//持久層抽象介面
com.belief.Impl----//持久層(DAO層)的實現類,繼承了持久層公共父類,並實現了持久層抽象介面
com.belief.model----//實體類
com.belief.util----//Hibernate靜態工具類
com.belief.test----//僅供測試
首先編寫com.belief.util下的Hibernate靜態工具類----HibernateUtil
package com.belief.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// 使用靜態程式碼塊初始化Hibernate
static {
try {
// 1 讀取配置檔案
Configuration cfg = new Configuration().configure();
// 2 根據配置 建立Factory
sessionFactory = cfg.buildSessionFactory();
cfg = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 獲得SessionFactory例項
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
// 獲得ThreadLocal物件管理的Session例項
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
// 3 通過sessionFactory獲得操作資料庫的session物件
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
// 從執行緒區域性變數threadLocal中獲取之前存入的Session例項
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
// 重建SessionFactory
public static void rebuildSessionFactory() {
try {
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
cfg = null;
} catch (Exception ex) {
System.out.println("Error Creating SessionFactory");
ex.printStackTrace();
}
}
public static void shutDown() {
getSessionFactory().close();
}
}
再編寫實體層以及Hibernate對映檔案
package com.belief.model;
import java.io.Serializable;
//聯合主鍵實體類必須實現序列化介面
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private String mail_address;
private String friend_address;
private String remark_name;
public String getMail_address() {
return mail_address;
}
public void setMail_address(String mail_address) {
this.mail_address = mail_address;
}
public String getFriend_address() {
return friend_address;
}
public void setFriend_address(String friend_address) {
this.friend_address = friend_address;
}
public String getRemark_name() {
return remark_name;
}
public void setRemark_name(String remark_name) {
this.remark_name = remark_name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((friend_address == null) ? 0 : friend_address.hashCode());
result = prime * result + ((mail_address == null) ? 0 : mail_address.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (friend_address == null) {
if (other.friend_address != null)
return false;
} else if (!friend_address.equals(other.friend_address))
return false;
if (mail_address == null) {
if (other.mail_address != null)
return false;
} else if (!mail_address.equals(other.mail_address))
return false;
return true;
}
@Override
public String toString() {
return "Address [mail_address=" + mail_address + ", friend_address=" + friend_address + ", remark_name="
+ remark_name + "]";
}
}
package com.belief.model;
//實體類
public class Adjunct {
private String mail_id;
private String adjunct_id;
private String adjunct_type;
private double adjunct_size;
private String adjunct_url;
public String getMail_id() {
return mail_id;
}
public void setMail_id(String mail_id) {
this.mail_id = mail_id;
}
public String getAdjunct_id() {
return adjunct_id;
}
public void setAdjunct_id(String adjunct_id) {
this.adjunct_id = adjunct_id;
}
public String getAdjunct_type() {
return adjunct_type;
}
public void setAdjunct_type(String adjunct_type) {
this.adjunct_type = adjunct_type;
}
public double getAdjunct_size() {
return adjunct_size;
}
public void setAdjunct_size(double adjunct_size) {
this.adjunct_size = adjunct_size;
}
public String getAdjunct_url() {
return adjunct_url;
}
public void setAdjunct_url(String adjunct_url) {
this.adjunct_url = adjunct_url;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((adjunct_id == null) ? 0 : adjunct_id.hashCode());
result = prime * result + ((adjunct_type == null) ? 0 : adjunct_type.hashCode());
result = prime * result + ((adjunct_url == null) ? 0 : adjunct_url.hashCode());
result = prime * result + ((mail_id == null) ? 0 : mail_id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Adjunct other = (Adjunct) obj;
if (adjunct_id == null) {
if (other.adjunct_id != null)
return false;
} else if (!adjunct_id.equals(other.adjunct_id))
return false;
if (adjunct_type == null) {
if (other.adjunct_type != null)
return false;
} else if (!adjunct_type.equals(other.adjunct_type))
return false;
if (adjunct_url == null) {
if (other.adjunct_url != null)
return false;
} else if (!adjunct_url.equals(other.adjunct_url))
return false;
if (mail_id == null) {
if (other.mail_id != null)
return false;
} else if (!mail_id.equals(other.mail_id))
return false;
return true;
}
@Override
public String toString() {
return "Adjunct [mail_id=" + mail_id + ", adjunct_id=" + adjunct_id + ", adjunct_type=" + adjunct_type
+ ", adjunct_size=" + adjunct_size + ", adjunct_url=" + adjunct_url + "]";
}
}
package com.belief.model;
//實體類
public class Admin {
private String account;
private String password;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((account == null) ? 0 : account.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Admin other = (Admin) obj;
if (account == null) {
if (other.account != null)
return false;
} else if (!account.equals(other.account))
return false;
return true;
}
@Override
public String toString() {
return "Admin [account=" + account + ", password=" + password + "]";
}
}
package com.belief.model;
import java.util.Date;
//實體類
public class Mail {
private String mail_id;
private String mail_address;
private String mail_receive;
private Date send_time;
private String mail_subject;
private String mail_content;
private String state_send;
private String state_read;
private String content_encoding;
private String protocol_version;
private Date timing;
public String getMail_id() {
return mail_id;
}
public void setMail_id(String mail_id) {
this.mail_id = mail_id;
}
public String getMail_address() {
return mail_address;
}
public void setMail_address(String mail_address) {
this.mail_address = mail_address;
}
public String getMail_receive() {
return mail_receive;
}
public void setMail_receive(String mail_receive) {
this.mail_receive = mail_receive;
}
public Date getSend_time() {
return send_time;
}
public void setSend_time(Date send_time) {
this.send_time = send_time;
}
public String getMail_subject() {
return mail_subject;
}
public void setMail_subject(String mail_subject) {
this.mail_subject = mail_subject;
}
public String getMail_content() {
return mail_content;
}
public void setMail_content(String mail_content) {
this.mail_content = mail_content;
}
public String getState_send() {
return state_send;
}
public void setState_send(String state_send) {
this.state_send = state_send;
}
public String getState_read() {
return state_read;
}
public void setState_read(String state_read) {
this.state_read = state_read;
}
public String getContent_encoding() {
return content_encoding;
}
public void setContent_encoding(String content_encoding) {
this.content_encoding = content_encoding;
}
public String getProtocol_version() {
return protocol_version;
}
public void setProtocol_version(String protocol_version) {
this.protocol_version = protocol_version;
}
public Date getTiming() {
return timing;
}
public void setTiming(Date timing) {
this.timing = timing;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mail_address == null) ? 0 : mail_address.hashCode());
result = prime * result + ((mail_id == null) ? 0 : mail_id.hashCode());
result = prime * result + ((mail_receive == null) ? 0 : mail_receive.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Mail other = (Mail) obj;
if (mail_address == null) {
if (other.mail_address != null)
return false;
} else if (!mail_address.equals(other.mail_address))
return false;
if (mail_id == null) {
if (other.mail_id != null)
return false;
} else if (!mail_id.equals(other.mail_id))
return false;
if (mail_receive == null) {
if (other.mail_receive != null)
return false;
} else if (!mail_receive.equals(other.mail_receive))
return false;
return true;
}
@Override
public String toString() {
return "Mail [mail_id=" + mail_id + ", mail_address=" + mail_address + ", mail_receive=" + mail_receive
+ ", send_time=" + send_time + ", mail_subject=" + mail_subject + ", mail_content=" + mail_content
+ ", state_send=" + state_send + ", state_read=" + state_read + ", content_encoding=" + content_encoding
+ ", protocol_version=" + protocol_version + ", timing=" + timing + "]";
}
}
package com.belief.model;
//實體類
public class User {
private String nick_name;
private String mail_address;
private String user_password;
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getMail_address() {
return mail_address;
}
public void setMail_address(String mail_address) {
this.mail_address = mail_address;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mail_address == null) ? 0 : mail_address.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (mail_address == null) {
if (other.mail_address != null)
return false;
} else if (!mail_address.equals(other.mail_address))
return false;
return true;
}
@Override
public String toString() {
return "User [nick_name=" + nick_name + ", mail_address=" + mail_address + ", user_password=" + user_password
+ "]";
}
}
Address.hbm.xml
<?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.belief.model.Address" table="address_book">
<!-- 聯合主鍵關聯 -->
<composite-id>
<key-property name="mail_address" column="mail_address"></key-property>
<key-property name="friend_address" column="friend_address"></key-property>
</composite-id>
<!-- 屬性關聯-->
<property name="remark_name" column="remark_name"></property>
</class>
</hibernate-mapping>
Adjunct.hbm.xml
<?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.belief.model.Adjunct" table="adjunct">
<!-- 主鍵關聯 -->
<id name="adjunct_id" column="adjunct_id"></id>
<!-- 屬性關聯 -->
<property name="mail_id" column="mail_id"></property>
<property name="adjunct_type" column="adjunct_type"></property>
<property name="adjunct_size" column="adjunct_size"></property>
<property name="adjunct_url" column="adjunct_url"></property>
</class>
</hibernate-mapping>
Admin.hbm.xml
<?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.belief.model.Admin" table="admin">
<id name="account" column="account"></id>
<property name="password" column="password"></property>
</class>
</hibernate-mapping>
Mail.hbm.xml
<?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.belief.model.Mail" table="mail_entity">
<id name="mail_id" column="mail_id"></id>
<property name="mail_address" column="mail_address"></property>
<property name="mail_receive" column="mail_receive"></property>
<property name="send_time" column="send_time"></property>
<property name="mail_subject" column="mail_subject"></property>
<property name="mail_content" column="mail_content"></property>
<property name="state_send" column="state_send"></property>
<property name="state_read" column="state_read"></property>
<property name="content_encoding" column="content_encoding"></property>
<property name="protocol_version" column="protocol_version"></property>
<property name="timing" column="timing"></property>
</class>
</hibernate-mapping>
User.hbm.xml
<?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.belief.model.User" table="user_entity">
<id name="mail_address" column="mail_address"></id>
<property name="nick_name" column="nick_name"></property>
<property name="user_password" column="user_password"></property>
</class>
</hibernate-mapping>
-然後是五個DAO層抽象介面
package com.belief.dao;
import java.util.ArrayList;
import com.belief.model.Address;
//持久層抽象介面
public interface addressDao {
void save(Address address);
void delete(Address address);
void update(Address address);
Address QueryByOne(String mail_address, String friend_address);
ArrayList<Address> QueryByMail(String mail_address);
}
package com.belief.dao;
import java.util.ArrayList;
import com.belief.model.Adjunct;
//持久層抽象介面
public interface adjunctDao {
void save(Adjunct adjunct);
void delete(Adjunct adjunct);
void update(Adjunct adjunct);
Adjunct QueryById(String adjunct_id);
ArrayList <Adjunct> QueryByMailId(String mail_id);
}
package com.belief.dao;
import com.belief.model.Admin;
//持久層抽象介面
public interface adminDao {
void save(Admin admin);
void delete(Admin admin);
void update(Admin admin);
Admin QueryByAccount(String account);
}
package com.belief.dao;
import java.util.ArrayList;
import com.belief.model.Mail;
//持久層抽象介面
public interface mailDao {
void save(Mail mail);
void delete(Mail mail);
void update(Mail mail);
Mail QueryByMailId(String mail_id);
ArrayList <Mail> QueryByMailAddress(String mail_address);
ArrayList <Mail> QueryByMailReceive(String mail_receive);
}
package com.belief.dao;
import java.util.ArrayList;
import com.belief.model.User;
//持久層抽象介面
public interface userDao {
void save(User user);
void delete(User user);
void update(User user);
User QueryByEmail(String email);
ArrayList <User> QueryAllUser();
}
-五個DAO層實現類和一個實現類的公共父類
ImplFather.java
package com.belief.Impl;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.belief.util.HibernateUtil;
//提取持久層(DAO層)的公共部分,作為持久層實現類的公共父類
public class ImplFather {
protected Session session = HibernateUtil.getSession();
protected Transaction tx = session.beginTransaction();
protected void cleanUp() {
try {
tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
HibernateUtil.closeSession();
}
}
}
package com.belief.Impl;
import java.util.ArrayList;
import com.belief.dao.addressDao;
import com.belief.model.Address;
//持久層(DAO層)的實現類,繼承了持久層公共父類,並實現了持久層抽象介面
public class addressDaoImpl extends ImplFather implements addressDao {
@Override
public void save(Address address) {
session.save(address);
cleanUp();
}
@Override
public void delete(Address address) {
session.delete(address);
cleanUp();
}
@Override
public void update(Address address) {
session.update(address);
cleanUp();
}
@Override
public Address QueryByOne(String mail_address, String friend_address) {
String hql = "SELECT * FROM address_book WHERE mail_address=? AND friend_address=?";
Address address = (Address) session.createQuery(hql).setParameter(0, mail_address)
.setParameter(1, friend_address).uniqueResult();
cleanUp();
return address;
}
@Override
public ArrayList<Address> QueryByMail(String mail_address) {
String hql = "SELECT * FROM address_book WHERE mail_address=?";
@SuppressWarnings("unchecked")
ArrayList<Address> addresss = (ArrayList<Address>) session.createQuery(hql).setParameter(0, mail_address)
.getResultList();
cleanUp();
return addresss;
}
}
package com.belief.Impl;
import java.util.ArrayList;
import com.belief.dao.adjunctDao;
import com.belief.model.Adjunct;
//持久層(DAO層)的實現類,繼承了持久層公共父類,並實現了持久層抽象介面
public class adjunctDaoImpl extends ImplFather implements adjunctDao {
@Override
public void save(Adjunct adjunct) {
session.save(adjunct);
cleanUp();
}
@Override
public void delete(Adjunct adjunct) {
session.delete(adjunct);
cleanUp();
}
@Override
public void update(Adjunct adjunct) {
session.update(adjunct);
cleanUp();
}
@Override
public Adjunct QueryById(String adjunct_id) {
Adjunct adjunct = (Adjunct) session.get(Adjunct.class, adjunct_id);
cleanUp();
return adjunct;
}
@Override
public ArrayList<Adjunct> QueryByMailId(String mail_id) {
String hql = "SELECT * FROM adjunct WHERE mail_id=?";
@SuppressWarnings("unchecked")
ArrayList<Adjunct> adjuncts = (ArrayList<Adjunct>) session.createQuery(hql).setParameter("mail_id", mail_id)
.getResultList();
cleanUp();
return adjuncts;
}
}
package com.belief.Impl;
import com.belief.dao.adminDao;
import com.belief.model.Admin;
//持久層(DAO層)的實現類,繼承了持久層公共父類,並實現了持久層抽象介面
public class adminDaoImpl extends ImplFather implements adminDao {
@Override
public void save(Admin admin) {
session.save(admin);
cleanUp();
}
@Override
public void delete(Admin admin) {
session.delete(admin);
cleanUp();
}
@Override
public void update(Admin admin) {
session.update(admin);
cleanUp();
}
@Override
public Admin QueryByAccount(String account) {
Admin admin = (Admin) session.get(Admin.class, account);
cleanUp();
return admin;
}
}
package com.belief.Impl;
import java.util.ArrayList;
import com.belief.dao.mailDao;
import com.belief.model.Mail;
//持久層(DAO層)的實現類,繼承了持久層公共父類,並實現了持久層抽象介面
public class mailDaoImpl extends ImplFather implements mailDao {
@Override
public void save(Mail mail) {
session.save(mail);
cleanUp();
}
@Override
public void delete(Mail mail) {
session.delete(mail);
cleanUp();
}
@Override
public void update(Mail mail) {
session.update(mail);
cleanUp();
}
@Override
public Mail QueryByMailId(String mail_id) {
Mail mail = (Mail) session.get(Mail.class, mail_id);
cleanUp();
return mail;
}
@Override
public ArrayList<Mail> QueryByMailAddress(String mail_address) {
String hql = "SELECT * FROM mail_entity WHERE mail_address=?";
@SuppressWarnings("unchecked")
ArrayList<Mail> mails = (ArrayList<Mail>) session.createQuery(hql).setParameter("mail_address", mail_address)
.getResultList();
cleanUp();
return mails;
}
@Override
public ArrayList<Mail> QueryByMailReceive(String mail_receive) {
String hql = "SELECT * FROM mail_entity WHERE mail_receive=?";
@SuppressWarnings("unchecked")
ArrayList<Mail> mails = (ArrayList<Mail>) session.createQuery(hql).setParameter("mail_receive", mail_receive)
.getResultList();
cleanUp();
return mails;
}
}
package com.belief.Impl;
import java.util.ArrayList;
import com.belief.dao.userDao;
import com.belief.model.User;
//持久層(DAO層)的實現類,繼承了持久層公共父類,並實現了持久層抽象介面
public class userDaoImpl extends ImplFather implements userDao {
@Override
public void save(User user) {
session.save(user);
cleanUp();
}
@Override
public void delete(User user) {
session.delete(user);
cleanUp();
}
@Override
public void update(User user) {
session.update(user);
cleanUp();
}
@Override
public User QueryByEmail(String email) {
User user = (User) session.get(User.class, email);
cleanUp();
return user;
}
@Override
public ArrayList<User> QueryAllUser() {
String hql = "SELECT * FROM user_entity";
@SuppressWarnings("unchecked")
ArrayList<User> users = (ArrayList<User>) session.createQuery(hql).getResultList();
cleanUp();
return users;
}
}
最後,當然是寫一個測試類測試一下功能
package com.belief.test;
import org.junit.Test;
import com.belief.Impl.*;
import com.belief.model.User;
//僅供測試
public class TestUser {
// 測試增
@Test
public void testSave() {
userDaoImpl impl = new userDaoImpl();
User iuser = new User();
iuser.setMail_address("[email protected]");
iuser.setNick_name("佚陽");
iuser.setUser_password("LYY1115*");
impl.save(iuser);
}
// 測試查
@Test
public void testQuery() {
userDaoImpl impl = new userDaoImpl();
System.out.println(impl.QueryByEmail("[email protected]"));
}
// 測試改
@Test
public void testUpdate() {
userDaoImpl impl = new userDaoImpl();
User iuser = new User();
iuser.setMail_address("[email protected]");
iuser.setNick_name("陽陽陽陽");
iuser.setUser_password("LYY1145*");
impl.update(iuser);
}
// 測試刪
@Test
public void testdelete() {
userDaoImpl impl = new userDaoImpl();
User iuser = new User();
iuser.setMail_address("[email protected]");
impl.delete(iuser);
}
}