项目介绍
该项目适合作为ssm的入门项目,包含对数据库表信息的查询和修改,同时对数据库中的多个表进行多表查询并返回自定义的数据类型,还有在网站中进行文件上传等功能。在项目的后台可以进行专辑管理,流派管理,歌曲管理和歌手管理。在项目的前台可以分页查看歌手和歌曲,并进行歌曲的播放。
项目所需技术
1.java基础,java反射,泛型
2.html,css,JavaScript,jquery,bootstrap,layui
3.Servlet,过滤器,监听器,jstl,el表达式,jsp,mysql,jdbc,xml,javaweb
4.springmvc,mybatis,spring三大开发框架
5.Maven(聚合ssm),junit单元测试
6.jersy,图片服务器搭建(fastDFS)
7.idea开发工具,powerdesigner数据库建模,Navicat连接数据库工具
8.amchart报表开发
搭建数据库环境
创建数据库
设计数据库模型
sql导出文件
drop table if exists ALBUM;
drop table if exists COMMENT;
drop table if exists MTYPE;
drop table if exists SONG;
drop table if exists SONGER;
drop table if exists TX_USER;
/*==============================================================*/
/* Table: ALBUM */
/*==============================================================*/
create table ALBUM
(
AID int(10) not null auto_increment,
ANAME varchar(100),
PIC varchar(200),
COMPANY varchar(50),
PDATE date,
LANG varchar(50),
primary key (AID)
);
/*==============================================================*/
/* Table: COMMENT */
/*==============================================================*/
create table COMMENT
(
COMMENT_ID int(10) not null auto_increment,
COM_COMMENT_ID int(10),
USER_ID int(10),
COMMENT_CONTENT text,
Z_COUNT int(10),
primary key (COMMENT_ID)
);
/*==============================================================*/
/* Table: MTYPE */
/*==============================================================*/
create table MTYPE
(
TID int(10) not null auto_increment,
TNAME varchar(50),
TDESC varchar(100),
primary key (TID)
);
/*==============================================================*/
/* Table: SONG */
/*==============================================================*/
create table SONG
(
SID int(10) not null auto_increment,
TID int(10),
SRID int(10),
AID int(10),
SNAME varchar(50),
PIC varchar(100),
MP3 varchar(100),
LRC text,
IS_HOT int(2),
IS_NEW int(2),
PTIMES int(100),
AUDIT_STATUS int(2),
SHOW_STATUS int(2),
primary key (SID)
);
/*==============================================================*/
/* Table: SONGER */
/*==============================================================*/
create table SONGER
(
SRID int(10) not null auto_increment,
TID int(10),
SRNAME varchar(20),
INTRO text,
AREA varchar(20),
PIC varchar(100),
IS_HOT int(2),
primary key (SRID)
);
/*==============================================================*/
/* Table: TX_USER */
/*==============================================================*/
create table TX_USER
(
USER_ID int(10) not null auto_increment,
USERNAME varchar(20),
PASSWORD varchar(20),
QQ varchar(20),
EMAIL varchar(20),
NICK varchar(20),
TEL varchar(20),
REG_TIME date,
primary key (USER_ID)
);
数据库结果:
创建工程
在maven环境正确的条件下创建maven聚合项目如下:
ham-parent:父工程
ham-portal: 前台模块
ham-core: 底层公用的模块
ham-console: 后台模块
ham-file: 文件服务器模块
导入pom文件依赖
创建普通maven项目
导入父工程的pom依赖:
?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qcby</groupId>
<artifactId>hami_parent</artifactId>
<version>1.0-SNAPSHOT</version>
<!--maven的聚合项目体现-->
<modules>
<module>hami_core</module>
<module>hami_console</module>
<module>hami_portal</module>
<module>hami_file</module>
</modules>
<packaging>pom</packaging>
<!-- dependencyManagement父工程做jar包统一管理的标签 -->
<dependencyManagement>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- spring整合aop的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</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>
<!-- spring整合webmvc的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring整合test测试的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 事务的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring整合jdbc的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- servlet javaweb -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- jsp api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- jstl标签库的 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- spring整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- 连接池 开源 阿里巴巴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- fastjson json数据和实体类进行转换的 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- 文件上传处理 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!-- jstl标签库的 servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- 图片服务器的 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<!--maven统一管理jar包的版本号-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
<aspectj.version>1.6.8</aspectj.version>
<junit.version>4.12</junit.version>
<servlet.version>2.5</servlet.version>
<jsp.version>2.0</jsp.version>
<jstl.version>1.2</jstl.version>
<druid.version>1.1.10</druid.version>
<fastjson.version>1.2.47</fastjson.version>
<commons-io.version>2.0.1</commons-io.version>
<commons-lang.version>2.6</commons-lang.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-codec.version>1.10</commons-codec.version>
<mybatis-spring.version>1.3.0</mybatis-spring.version>
<jersey.version>1.2</jersey.version>
</properties>
</project>
在父工程中建立子工程
创建普通maven项目hami_file
该子工程用于文件的上传,例如网页中呈现的图片
该子项目中无需引入额外的依赖
创建普通maven项目hami_core
用于处理底层的逻辑
导入依赖:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>hami_parent</artifactId>
<groupId>com.qcby</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>hami_core</artifactId>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!--文件上传处理-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
</dependencies>
</project>
创建mavenWeb项目hami_console
该子模块用于呈现网页的后台界面
导入pom依赖:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>hami_parent</artifactId>
<groupId>com.qcby</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!--后台有界面 用户访问 war包-->
<artifactId>hami_console</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.qcby</groupId>
<version>1.0-SNAPSHOT</version>
<artifactId>hami_core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
</dependencies>
</project>
创建mavenWeb项目hami_portal
用于呈现网页前台界面
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>hami_parent</artifactId>
<groupId>com.qcby</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!--前台有界面 用户访问 war包-->
<artifactId>hami_portal</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.qcby</groupId>
<version>1.0-SNAPSHOT</version>
<artifactId>hami_core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
</project>
搭建mybatis和spring的架构
建包
在ham-core中java资源包下创建包如图所示
resources资源包下引入
日志文件log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
数据库连接文件:jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///hami
jdbc.username=root
jdbc.password=202306
逆向工程
使用逆向工程来快速生成文件来减少重复性操作
在core工程中的resources文件夹下加入配置文件generatorConfig.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="mybatisGenerator" >
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/hami?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true"
userId="root"
password="202306">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.qcby.model"
targetProject=".\hami_core\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject=".\hami_core\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 指定数据库表 -->
<table tableName="songer" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
在util文件夹下中创建逆向工程的执行类
package com.qcby.util;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
public class Generator {
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
/**指向逆向工程配置文件*/
File configFile = new File("hami_core/src/main/resources/generatorConfig.xml");
ConfigurationParser parser = new ConfigurationParser(warnings);
Configuration config = parser.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws Exception {
try {
Generator generatorSqlmap = new Generator();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行类运行结束后会根据配置文件中的数据库表来创建文件
例如当前指定的数据库表为songer
执行完后就会自动生成model文件下的songer实体类和resources/mapper下生成数据层sql执行配置文件SongMapper.xml,用来执行具体的SQL语句
数据库中其他表也可以用此方法来创建数据层和实体类文件,只需修改配置文件中的tableName即可
创建mybatis的全局配置文件
在resources里面创建sqlMapConfig.xml
注册映射配置文件,该项目中设计四张表的操作,因此映射四个文件,这几个文件是通过逆向工程得到的
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="mapper/MtypeMapper.xml"/>
<mapper resource="mapper/AlbumMapper.xml"/>
<mapper resource="mapper/SongerMapper.xml"/>
<mapper resource="mapper/SongMapper.xml"/>
</mappers>
</configuration>
创建spring的配置文件
在resources文件下创建beans.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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启扫描包的位置-->
<context:component-scan base-package="com.qcby"></context:component-scan>
<!--加载连接数据库的参数文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--创建和数据库连接的会话工厂对象交给spring管理
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
优化直接加载sql文件,省略mybatis的总配置文件
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<!--扫描dao文件-->
<bean id="mapperScan" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.qcby.dao"></property>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"></tx:method>
<tx:method name="select" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.qcby.service..*.*(..))"></aop:advisor>
</aop:config>
</beans>
抽取公共代码
因为对数据库中每一张表的增删改查操作都有很大一部分是重复的,因此可以创建一个公共实现类来减少我们写重复的代码,使用时采用继承即可
创建公共的service层接口
每一张表的实现类可以使用公共实现类中的方法
在service文件中创建BaseService文件
代码如下:
package com.qcby.service;
import com.qcby.util.Page;
/**
* 业务层公共接口
* @param <T> 泛型
*/
public interface BaseService<Q,T> {
int deleteByPrimaryKey(Integer tid);
int insert(T record);
int insertSelective(T record);
T selectByPrimaryKey(Integer tid);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
}
T用来传入参数
Q用来分页查询传递的参数
创建公共Service的实现类
package com.qcby.service.impl;
import com.qcby.dao.BaseDao;
import com.qcby.service.BaseService;
import com.qcby.util.Page;
import java.lang.reflect.Method;
import java.util.List;
public class BaseServiceImpl<Q,T> implements BaseService<Q,T> {
protected BaseDao<Q,T> baseDao;
@Override
public int deleteByPrimaryKey(Integer tid) {
return baseDao.deleteByPrimaryKey(tid);
}
@Override
public int insert(T t) {
return baseDao.insert(t);
}
@Override
public int insertSelective(T t) {
return baseDao.insert(t);
}
@Override
public T selectByPrimaryKey(Integer tid) {
return baseDao.selectByPrimaryKey(tid);
}
@Override
public int updateByPrimaryKeySelective(T t) {
return baseDao.updateByPrimaryKeySelective(t);
}
@Override
public int updateByPrimaryKey(T t) {
return baseDao.updateByPrimaryKey(t);
}
}
创建持久层的公共接口
在dao文件夹下创建BaseDao文件作为公共接口
package com.qcby.dao;
import java.util.List;
/**
* 持久层公共接口
* @param <T>
*/
public interface BaseDao<Q,T> {
int deleteByPrimaryKey(Integer tid);
int insert(T record);
int insertSelective(T record);
T selectByPrimaryKey(Integer tid);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
List<T> selectPage(Q mq);
Integer selectCount(Q mq);
}
创建具体的接口与实现类
根据数据库中表的名字创建接口和实现类,后面的文件通过下面要说的代码生成器直接生成,不必再自己写,下方只是举个例子来说明具体的实现类接口的样子,
例如创建songer表的接口和实现类,全部继承公共代码
SongerService接口
public interface SongerService extends BaseService<SongerQuery,Songer>{
}
实现类
@Service
public class SongerServiceImpl extends BaseServiceImpl<SongerQuery,Songer> implements SongerService {
private SongerMapper songerMapper;
@Autowired
public void setSongerMapper(SongerMapper songerMapper) {
this.songerMapper = songerMapper;
this.baseDao=songerMapper;
}
}
代码生成器
在src/test/resources资源包下创建模板文件
该模板文件作为模板来创建具体的文件
1.DemoMapper.tpl
package com.qcby.dao;
import com.qcby.model.Demo;
public interface DemoMapper extends BaseDao<DemoQuery,Demo>{
}
2.DemoQuery.tpl
package com.qcby.query;
import com.qcby.model.Demo;
/**
* 只作为表现层接收前端参数封装使用
*/
public class DemoQuery extends Demo{
}
3.DemoService.tpl
package com.qcby.service;
import com.qcby.model.Demo;
public interface DemoService extends BaseService<DemoQuery,Demo>{
}
4.DemoServiceImpl.tpl
package com.qcby.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qcby.dao.DemoMapper;
import com.qcby.model.Demo;
import com.qcby.service.DemoService;
@Service
public class DemoServiceImpl extends BaseServiceImpl<DemoQuery,Demo> implements DemoService {
private DemoMapper demoMapper;
@Autowired
public void setDemoMapper(DemoMapper demoMapper) {
this.demoMapper = demoMapper;
this.baseDao=demoMapper;
}
}
代码生成器执行类:
在util文件夹下创建SourceCenerator类
package com.qcby.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
/**
* 代码生成器执行类
*/
public class SourceGenerator {
public static void main(String[] args) throws Exception {
generatorSource("Songer");
}
public static void generatorSource(String objName) throws Exception{
generateQuery(objName);
generateDao(objName);
generateService(objName);
generateServiceImpl(objName);
}
public static void generateQuery(String objName) throws Exception{
//EbItem
//创建文件输入流
BufferedReader br = new BufferedReader(new FileReader("hami_core/src/test/resources/tpl/DemoQuery.tpl"));
BufferedWriter bw = new BufferedWriter(new FileWriter("hami_core/src/main/java/com/qcby/query/"+objName+"Query.java"));
String line = null;
while((line = br.readLine()) != null){
line = line.replace("Demo", objName);
bw.write(line);
bw.newLine();
}
bw.close();
br.close();
}
public static void generateDao(String objName) throws Exception{
//EbItem
//创建文件输入流
BufferedReader br = new BufferedReader(new FileReader("hami_core/src/test/resources/tpl/DemoMapper.tpl"));
BufferedWriter bw = new BufferedWriter(new FileWriter("hami_core/src/main/java/com/qcby/dao/"+objName+"Mapper.java"));
String line = null;
while((line = br.readLine()) != null){
line = line.replace("Demo", objName);
bw.write(line);
bw.newLine();
}
bw.close();
br.close();
}
public static void generateService(String objName) throws Exception{
//EbItem
//创建文件输入流
BufferedReader br = new BufferedReader(new FileReader("hami_core/src/test/resources/tpl/DemoService.tpl"));
BufferedWriter bw = new BufferedWriter(new FileWriter("hami_core/src/main/java/com/qcby/service/"+objName+"Service.java"));
String line = null;
while((line = br.readLine()) != null){
line = line.replace("Demo", objName);
bw.write(line);
bw.newLine();
}
bw.close();
br.close();
}
public static void generateServiceImpl(String objName) throws Exception{
//把传递过来的实体类的名字改成小写一份
String lowerObjName = objName.substring(0, 1).toLowerCase()+objName.substring(1, objName.length());
//EbItem
//创建文件输入流
BufferedReader br = new BufferedReader(new FileReader("hami_core/src/test/resources/tpl/DemoServiceImpl.tpl"));
BufferedWriter bw = new BufferedWriter(new FileWriter("hami_core/src/main/java/com/qcby/service/impl/"+objName+"ServiceImpl.java"));
String line = null;
while((line = br.readLine()) != null){
line = line.replace("Demo", objName);
line = line.replace("demo", lowerObjName);
bw.write(line);
bw.newLine();
}
bw.close();
br.close();
}
}
通过修改主方法中字符串来自动生成Dao接口,Service接口和实现类,管理分页查询的类(该类在下一篇文章中会有解释)
修改字符串执行完成后就可以完成所有类的生成,生成完后结构如下:
至此,前面的准备工作彻底完成,下篇文章开始进行项目后台的搭建