DAO层实现示例 序


项目地址:
https://github.com/FateSolo/DAO-Test

目录:

该系列文章将展示六种不同的DAO层实现方法并总结其不同,本章将首先完成项目总体结构的搭建。

项目环境:

  • Ubuntu 14.04.3
  • Intellij IDEA 15.0.2

1. 项目搭建:

1) 打开IDEA,点击Create New Project,在左侧边栏找到Gradle,并勾选Java和Web,JDK选择1.8。

2) 点击Next,GroupId:com.fatesolo;ArtifactId:DAO-Test。

3) 点击Next,勾选Use auto-import和Create directories for…。

4) 点击Next,直接Finish即完成了项目的创建。

5) 创建包和配置文件,如图:
01

2. 编写web.xml

1) 打开web.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
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

version="3.0">


<!-- Spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-common.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Spring MVC -->
<servlet>
<servlet-name>springMVC</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>
</init-param>

<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>

<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

2) 打开build.gradle文件, 在dependencies中,加入相关依赖:

1
compile 'org.springframework:spring-web:4.3.7.RELEASE'
compile 'org.springframework:spring-webmvc:4.3.7.RELEASE'

3. 编写相关配置文件

1) 打开db.properties文件,代码如下:

1
jdbc.url=jdbc:mysql://localhost:3306/dao_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

druid.initialSize=5
druid.minIdle=5
druid.maxActive=50

注意数据库名、用户名和密码都更改成你自己的。

2) 打开spring-mvc.xml,编写如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">


<context:component-scan base-package="com.fatesolo" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<mvc:annotation-driven/>

</beans>

3) 打开spring-common.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
47
48
49
50
51
52
53
54
55
56
<?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">


<context:component-scan base-package="com.fatesolo">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- 引入 db.properties 配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>

<!-- 数据源, 使用了Druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>

<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${druid.initialSize}"/>
<property name="minIdle" value="${druid.minIdle}"/>
<property name="maxActive" value="${druid.maxActive}"/>

<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>

<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>

<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>

<property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>

<property name="poolPreparedStatements" value="false"/>
</bean>

<!-- 配置事务 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<tx:annotation-driven transaction-manager="txManager"/>

</beans>

4) 打开build.gradle,加入如下依赖:

1
compile 'com.alibaba:druid:1.0.28'
compile 'mysql:mysql-connector-java:6.0.5'
compile 'org.springframework:spring-orm:4.3.7.RELEASE'

4. 编写基础代码

1) 这里以对书籍的增删改查为例,首先在MySQL数据库中创建数据库与表,并编写对应的实体类,这里只给出实体类Book的代码:

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
package com.fatesolo.entity;

public class Book {

private int id;

private String name;

private String author;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
}

}

2) 创建公共接口BookDao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.fatesolo.dao;

import com.fatesolo.entity.Book;

import java.util.List;

public interface BookDao {

/**
* 查找指定id的书籍
*/

Book findById(int id);

/**
* 查找包含该名字的所有书籍
*/

List<Book> findByNameContaining(String name);

/**
* 保存书籍
*/

void save(Book book);

}

3) 创建BookService

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
package com.fatesolo.service;

import com.fatesolo.dao.BookDao;
import com.fatesolo.entity.Book;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class BookService {

@Resource
private BookDao bookDao;

public Book getBookById(int id) {
return bookDao.findById(id);
}

public List<Book> getBooksByName(String name) {
return bookDao.findByNameContaining(name);
}

public boolean addBook(Book book) {
bookDao.save(book);

return book.getId() != 0;
}

}

4) 创建BookController

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
package com.fatesolo.controller;

import com.fatesolo.entity.Book;
import com.fatesolo.service.BookService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(path = "/book", produces = "application/json;charset=UTF-8")
public class BookController {

@Resource
private BookService bookService;

@RequestMapping(path = "/{id}", method = RequestMethod.GET)
public String getBookById(@PathVariable int id) {
Book book = bookService.getBookById(id);

return book != null ? book.toString() : "Not Found";
}

@RequestMapping(path = "/name/{name}", method = RequestMethod.GET)
public String getBooksByName(@PathVariable String name) {
List<Book> books = bookService.getBooksByName(name);

return books.size() != 0 ? books.toString() : "Not Found";
}

@RequestMapping(path = "", method = RequestMethod.POST)
public String addBook(Book book) {
return bookService.addBook(book) ? book.toString() : "Failure";
}

}

至此,项目总体结构搭建完毕。


作者 [@FateSolo]
2017 年 03月 12日