SpringMVC 4 + Hibernate 5連接MySQL 8的設定如下。
MySQL mydb
資料庫中MEMBER
資料表設定。
CREATE TABLE `member` (
`member_id` int(10) unsigned NOT NULL COMMENT '會員編號',
`member_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '會員信箱',
`member_name` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '會員名稱',
`password` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '密碼',
`register_time` datetime DEFAULT NULL COMMENT '註冊時間',
`login_time` datetime DEFAULT NULL COMMENT '登入時間',
`update_time` datetime DEFAULT NULL COMMENT '修改時間',
PRIMARY KEY (`member_id`),
UNIQUE KEY `member_email_UNIQUE` (`member_email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
MEMBER
資料表中的資料。
+-----------+--------------+-------------+----------+---------------------+------------+-------------+
| member_id | member_email | member_name | password | register_time | login_time | update_time |
+-----------+--------------+-------------+----------+---------------------+------------+-------------+
| 1 | matt@123.com | matthung | 12345 | 2018-05-12 00:00:00 | NULL | NULL |
+-----------+--------------+-------------+----------+---------------------+------------+-------------+
Maven Web專案建立好後,在pom.xml
加入dependency設定如下來載入所需的函式庫。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>idv.matt</groupId>
<artifactId>demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- spring transaction manager -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- Hibernate -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.12.Final</version>
</dependency>
</dependencies>
<build>
<finalName>demo</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version><!-- Servlet 3.1-->
<configuration>
<source>1.8</source><!-- source compile Java version -->
<target>1.8</target><!-- target compile Java version -->
</configuration>
</plugin>
</plugins>
</build>
</project>
接著在web.xml
進行Spring MVC的相關配置,重點在於Spring應用程式環境(ApplicationContext)及SpringMVC Web環境(WebApplicationContext)的配置檔位置的設定。
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>demo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value> <!-- Spring ApplicationContext location -->
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value> <!-- Spring WebApplicationContext location -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
根據以上設定Spring的應用環境設定檔為classpath下的applicationContext.xml
,SpringMVC的Web環境設定檔為classpath下的spring-mvc.xml
。
接著設定applicationContext.xml
。
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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http://www.springframework.org/schema/security"
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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:annotation-config/>
<context:component-scan
base-package="idv.matt.controller,
idv.matt.service,
idv.matt.dao,
idv.matt.model" />
<mvc:default-servlet-handler />
<!-- MySQL dataSource config -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8" />
<property name="username" value="matt" />
<property name="password" value="12345" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="idv.matt.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
在applicationContext.xml
中設定連結MySQL的dataSource。因為要連接的MySQL版本是8,所以driverClassName
是com.mysql.cj.jdbc.Driver
。
對Spring component的掃描也在這進行設定。
接著設定spring-mvc.xml
。
spring-mvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
接著建立以下介面及類別。
idv.matt.controller.HelloController
idv.matt.service.MemberService
idv.matt.service.MemberServiceImpl
idv.matt.dao.MemberDao
idv.matt.dao.MemberDaoImpl
idv.matt.model.Member
HelloController.java
package idv.matt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import idv.matt.model.Member;
import idv.matt.service.MemberService;
@Controller
public class HelloController {
@Autowired
private MemberService memberService;
@RequestMapping(value="/hello")
public String hello() {
Member member = memberService.getMember(1);
System.out.println(member.getMemberName());
System.out.println(member.getRegisterTime());
return "hello";
}
}
HelloController
用來接收index.jsp
發出的request,呼叫service存取資料庫,然後返回hello.jsp
。
MemberService.java
package idv.matt.service;
import idv.matt.model.Member;
public interface MemberService {
public Member getMember(Integer memberId);
}
MemberServiceImpl.java
package idv.matt.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import idv.matt.dao.MemberDao;
import idv.matt.model.Member;
@Service("memberService")
public class MemberServiceImpl implements MemberService {
@Autowired
private MemberDao memberDao;
@Transactional
@Override
public Member getMember(Integer memberId) {
return memberDao.getMember(memberId);
}
}
存取映射資料的方法前必須加上@Transactional
交易管理注釋,否則會出現錯誤如下。
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
MemberDao.java
package idv.matt.dao;
import idv.matt.model.Member;
public interface MemberDao {
Member getMember(Integer memberId);
}
MemberDaoImpl.java
package idv.matt.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import idv.matt.model.Member;
@Repository("memberDao")
public class MemberDaoImpl implements MemberDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public Member getMember(Integer memberId) {
return sessionFactory.getCurrentSession().get(Member.class, memberId);
}
}
在MemberDaoImpl.getMember()
中呼叫Hiberante的Session.get(Class<T> entityType, Serializable id)
並傳入id來取得MEMBER
資料表中的資料並返回映射的Member
物件。
Member.java
package idv.matt.model;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name="MEMBER",
uniqueConstraints = {@UniqueConstraint(columnNames={"MEMBER_ID"})})
public class Member {
@Id
@Column(name="MEMBER_ID")
private Integer memberId;
@Column(name="MEMBER_EMAIL", length=100, nullable=false)
private String memberEmail;
@Column(name="MEMBER_NAME", length=30)
private String memberName;
@Column(name="PASSWORD", length=64, nullable=false)
private String password;
@Column(name="REGISTER_TIME")
private Timestamp registerTime;
@Column(name="LOGIN_TIME")
private Timestamp loginTime;
@Column(name="UPDATE_TIME")
private Timestamp updateTime;
public Member() {}
public Integer getMemberId() {
return memberId;
}
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
public String getMemberEmail() {
return memberEmail;
}
public void setMemberEmail(String memberEmail) {
this.memberEmail = memberEmail;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Timestamp getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Timestamp registerTime) {
this.registerTime = registerTime;
}
public Timestamp getLoginTime() {
return loginTime;
}
public void setLoginTime(Timestamp loginTime) {
this.loginTime = loginTime;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
}
idv.matt.model.Member
類別與資料庫的MEMBER
資料表作ORM。
接著頁面index.jsp
及/view/hello.jsp
,在index.jsp
有呼叫HelloController
的連結,而hello.jsp
為HelloController
返回的結果。
index.java
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<a href="hello">hello</a>
</body>
</html>
hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
完成以上便可以啟動MySQL資料庫及並執行專案,如果執行結果正確可以觀察到console會印出以下。
Hibernate: select member0_.MEMBER_ID as MEMBER_I1_0_0_, member0_.LOGIN_TIME as LOGIN_TI2_0_0_, member0_.MEMBER_EMAIL as MEMBER_E3_0_0_, member0_.MEMBER_NAME as MEMBER_N4_0_0_, member0_.PASSWORD as PASSWORD5_0_0_, member0_.REGISTER_TIME as REGISTER7_0_0_, member0_.UPDATE_TIME as UPDATE_T8_0_0_ from MEMBER member0_ where member0_.MEMBER_ID=?
matthung
2018-05-12 08:00:00.0
專案結構目錄
參考:
MemverServiceImpl.java <<檔名 是不是錯了? 應該是MebverServiceImpl.java
回覆刪除阿,是我寫錯了,感謝您的糾正,是MemberServiceImpl。
回覆刪除