Hibernate(IDEA) —— 搭建Hibernate專案
阿新 • • 發佈:2018-12-15
1、新增依賴
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <spring.version>4.3.18.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--log4j 日誌包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency> <!--Spring 框架核心庫 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring Web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- cglib --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.7</version> </dependency> <!-- aspectJ AOP 織入器 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.6</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <!--Spring java 資料庫訪問包,主要用於提供資料來源 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.3.6.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>5.3.6.Final</version> </dependency> <!--c3p0 連線池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--mysql 資料庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.17</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.17</version> </dependency> <!-- servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- jsp-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope></dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
2、新增log4j.properties配置
log4j.rootLogger=DEBUG,console log4j.logger.org.springframework.beans.factory=DEBUG log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.s=console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.appender.org.apache=INFO
3、新增applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--掃描類包以啟動註解驅動的 Bean--> <context:component-scan base-package="com.etc" /> <!-- 定義資料來源 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!--掃描基於 JPA 註解實體類包--> <property name="packagesToScan"> <list> <value>com.etc.entity</value> </list> </property><property name="hibernateProperties"> <props> <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/ssh</prop> <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop> <prop key="hibernate.connection.username">root</prop> <prop key="hibernate.connection.password">1234</prop> <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <!--定義 HibernateTemplate--> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置 Hibernate 事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 開啟註解式事務管理 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
4、建立資料庫表,資料庫名為ssh
create table t_department
(
id bigint not null auto_increment,
dept_name varchar(20) not null,
remark varchar(200) null,
primary key(id)
);
insert into t_department(dept_name,remark) values('總管理部','負責綜合管理工作');
insert into t_department(dept_name,remark) values('開發部','負責軟體的研發工作');
insert into t_department(dept_name,remark) values('人事部','負責人事管理工作');
insert into t_department(dept_name,remark) values('財務部','負責財務管理工作');
insert into t_department(dept_name,remark) values('市場部','負責市場開拓工作');
insert into t_department(dept_name,remark) values('測試部','負責軟體的測試工作');
create table t_user
(
id bigint not null auto_increment,
user_no varchar(20) not null, #賬號
user_name varchar(20) not null, #使用者名稱
password varchar(20) not null,#密碼
birthday date null,#生日
hire_date date null, #入職日期
department_id bigint null, #所在部門
active_flag smallint default 1,#是否有效,預設為有效
primary key(id)
);
-- 增加外來鍵約束
alter table t_user add constraint fk_department_id foreign key (department_id) references
t_department(id) ON DELETE CASCADE ON UPDATE CASCADE ;
insert into t_user(id,user_no,user_name,password,department_id) values(1,'admin','管理員
','123456',1);
5、IDEA中連線資料庫
單擊“Download”下載驅動,下載驅動後,即可進行連線測試:
單擊“OK”,IDEA 右側顯示“database”檢視:
6、反向工程 生成實體類
也可以通過 View->Tool Windows->Persitence,顯示 Persitence 視窗 選擇專案,右鍵-->Add Frameworks Support-->勾選 Hibernate-->勾選Import database schema-->OK
選擇好data source,點選package,建立一個新包,比如 com.etc.entity
選擇資料庫中的表和Session Factory,生成實體類 檢視生成的實體類資訊
JPA 提供的四種標準用法為 TABLE,SEQUENCE,IDENTITY,AUTO。 TABLE:使用一個特定的資料庫表格來儲存主鍵。 SEQUENCE:根據底層資料庫的序列來生成主鍵,條件是資料庫支援序列。 IDENTITY:主鍵由資料庫自動生成(主要是自動增長型)。 AUTO:主鍵由程式控制。 對實體類id新增如下:
@GeneratedValue(strategy = GenerationType.IDENTITY)
如何再次生成實體類
7、建立 Dao 基類
package com.etc.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
public class BaseDao<T> {
private Class<T> entityClass;
@Autowired
private HibernateTemplate hibernateTemplate;
//通過反射獲取子類確定的泛型類
public BaseDao() {
Type genType = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
entityClass = (Class) params[0];
}
@Transactional
public T load(Serializable id) {
return (T) hibernateTemplate.load(entityClass, id);
}
public T get(Serializable id) {
return (T) hibernateTemplate.get(entityClass, id);
}
public List<T> loadAll() {
return hibernateTemplate.loadAll(entityClass);
}
@Transactional
public void save(T entity) {
hibernateTemplate.save(entity);
}
@Transactional
public void update(T entity) {
hibernateTemplate.update(entity);
}
@Transactional
public void saveOrUpdate(T entity) {
hibernateTemplate.saveOrUpdate(entity);
}
@Transactional
public void delete(T entity) {
hibernateTemplate.delete(entity);
}
public List find(String hql) {
return hibernateTemplate.find(hql);
}
public List find(String hql, Object... params) {
return hibernateTemplate.find(hql, params);
}
public void initialize(Object entity) {
hibernateTemplate.initialize(entity);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
}
8、建立 UserDao
package com.etc.dao;
import com.etc.entity.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
public class UserDao extends BaseDao<User> {
public List<User> queryByUsernoAndPwd(String userNo,String password){
//String hql = "from User where userNo = ?0 and password = ?1 and activeFlag = 1";
//在使用者表中通過active_flag欄位來體現使用者是否有效
String hql = "from User where userNo = ?0 and password = ?1";
return (List<User>)find(hql,userNo,password);
}
}
9、測試
package com.etc.dao;
import com.etc.entity.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class TestUserDao {
private ClassPathXmlApplicationContext context;
private UserDao userDao;
@Before
public void before(){
System.out.println("init is completed");
context = new ClassPathXmlApplicationContext("applicationContext.xml");
userDao = context.getBean(UserDao.class);
}
@Test
public void testQueryByUsernoAndPwd(){
List<User> users = userDao.queryByUsernoAndPwd("admin","123456");
System.out.println(users);
}
@Test
public void testLoad(){
User user = userDao.load(1L);
System.out.println(user);
}
@Test
public void testGet(){
User user = userDao.get(2L);
System.out.println(user);
}
@Test
public void testInsert(){
User user = new User();
user.setUserNo("test2");
user.setUserName("測試人員2");
user.setPassword("123456");
userDao.save(user);
}
@Test
public void testLoadAll(){
List<User> users = userDao.loadAll();
System.out.println(users);
}
@Test
public void testUpdate(){
//User user = userDao.get(3L);
//user.setPassword("654321");
User user = new User();
user.setId(3L);
user.setUserNo("test3");
user.setUserName("測試人員3");
user.setPassword("123456");
userDao.update(user);
}
@Test
public void testSaveOrUpdate(){
User user = new User();
user.setId(10L);
user.setUserNo("test31");
user.setUserName("測試人員31");
user.setPassword("1234567");
userDao.saveOrUpdate(user);
}
@Test
public void testDelete(){
User user = userDao.get(4L);
userDao.delete(user);
}
@After
public void after(){
System.out.println("context is free");
context.close();
}
}