SSM项目实战哈米音乐01---项目环境搭建、公共模块

发布于:2024-11-29 ⋅ 阅读:(23) ⋅ 点赞:(0)

目录

1 项目所需技术

2.搭建数据库环境

2.1创建数据库

2.2设计数据库模型

2.3数据库的导出脚本

2.4maven环境搭建

1.设置maven本地仓库

2.设置环境变量

2.5idea的配置

3.maven项目

1.Maven的依赖管理在架构中的使用

2. Maven的项目构建在架构的使用

4.创建工程

1.加入pom文件的依赖

2.搭建mybatis和spring的架构

创建包结构

逆向工程

在utils目录下创建逆向工程的执行类Generator

创建Service层

创建mybatis的全局配置文件

创建spring的配置文件

创建测试整合

5.公共的代码抽取

1.创建baseDao

2.创建公共的Service接口

3.创建公共的Service接口实现类

6.代码生成器

7.代码生成器的工具类


1 项目所需技术

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报表开发

2.搭建数据库环境

2.1创建数据库

2.2设计数据库模型

2.3数据库的导出脚本

/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2019/10/12 9:55:56                           */
/*==============================================================*/


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)
);

2.4maven环境搭建

1.设置maven本地仓库

这里省略,可以查看我有关maven的文章Maven--架构项目管理工具icon-default.png?t=O83Ahttps://blog.csdn.net/jlihan/article/details/143089422?spm=1001.2014.3001.5502

2.设置环境变量

同上

2.5idea的配置

1.配置jdk

2.配置maven

3.maven项目

互联网的特点是后台和前台都需要开发:

前台:互联网用户访问的系统,对性能要求比较高。

后台:管理员访问的系统

前台和后台都包括前端和后端

1.Maven的依赖管理在架构中的使用

前台、后台、图片服务器:mavenJavaWeb项目

Core、Parent:mavenJava项目

2. Maven的项目构建在架构的使用

项目的构建

Source:必须要符合maven的目录结构

Project

        Src/main/java

        Src/main/resources

        Src/test/java

        Src/test/resources

        Pom.xml

mvn clean package

4.创建工程

ham-parent:父工程---普通maven项目

        ham-portal: 前台模块---mavenWeb项目

        ham-core:  底层公用的模块---普通maven项目

        ham-console: 后台模块---mavenWeb项目

        ham-file: 文件服务器模块---mavenWeb项目,此模块用于处理文件的上传,如图片,音频等

1.加入pom文件的依赖

子模块要继承父模块,父模块要聚合子模块

将父模块的打包方式写为 pom

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>cn.tx.music</groupId>
  <artifactId>ham-parent</artifactId>
  <version>1.0-SNAPSHOT</version>
  <!-- maven的聚合项目的体现 -->
  <modules>
    <module>ham-portal</module>
    <module>ham-core</module>
    <module>ham-console</module>
    <module>ham-file</module>
  </modules>
  <packaging>pom</packaging>

  <!-- 集中管理所有子模块的依赖版本和范围-->
  <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 API: HttpServlet  ServletRequest ServletResponse。。。 -->
      <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 -->
      <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>

公共模块ham-core的pom.xml

<?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>ham-parent</artifactId>
        <groupId>cn.tx.music</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ham-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>
        <!-- 反向工程的jar包 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>
    </dependencies>

</project>

前台模块ham-portal的pom.xml

<?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>ham-parent</artifactId>
        <groupId>cn.tx.music</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ham-portal</artifactId>
    <packaging>war</packaging>

    <name>ham-portal</name>

    <dependencies>
        <dependency>
            <groupId>cn.tx.music</groupId>
            <version>1.0-SNAPSHOT</version>
            <artifactId>ham-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>

后台模块ham-console的pom.xml

<?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>ham-parent</artifactId>
        <groupId>cn.tx.music</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ham-console</artifactId>
    <packaging>war</packaging>

    <name>ham-console</name>

    <dependencies>

        <dependency>
            <groupId>cn.tx.music</groupId>
            <version>1.0-SNAPSHOT</version>
            <artifactId>ham-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>

2.搭建mybatis和spring的架构

创建包结构

在ham-core中

resources资源包下引入

        日志文件log4j.properties

        数据库连接文件:db.properties (jdbc.properties)

db.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql:///ham?characterEncoding=utf-8
uname=root
pword=2020

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

逆向工程

在core工程中resource目录下加入配置文件generatorConfig.xml

创建其他表的逆向工程只需在 tableName这里修改表名

如果是其他包结构名称注意修改路径

<?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/ham?serverTimezone=CTT&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true"
                        userId="root"
                        password="2020">
        </jdbcConnection>

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="cn.tx.model"
                            targetProject=".\ham-core\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject=".\ham-core\src\main\resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cn.tx.dao"
                             targetProject=".\ham-core\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table tableName="songer" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"/>
        <!-- 有些表的字段需要指定java类型
         <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> -->
    </context>
</generatorConfiguration>
在utils目录下创建逆向工程的执行类Generator

逆向工程工具类

做逆向工程的

快速生成实体类、持久层接口、以及xml映射文件,减少重复性操作

基础CURD(增删改查)完成

如果重复点击,dao层,model层都会重新覆盖,但是创建的mapper.xml不会覆盖,其内容会重复,要删除重复才能使用

package cn.tx.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.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 逆向工程工具类
 * 做逆向工程的
 * 生成所有表的 实体 持久层接口 以及sql文件
 * 基础CURD(增删改查)完成
 */
public class Generator {

    /**
     * 定义做逆向工程的方法
     * @throws Exception
     */
    public void generator() throws Exception{
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        /** 指向逆向工程配置文件*/
        File configFile = new File("ham-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();
        }
    }
}

执行逆向工程后,就会我们的项目中就会生成下面的代码

逆向工程做完后我们已经有了数据层和model

在生成的model下的文件中补充有参构造器、无参构造器、toString方法、实现序列化

package cn.tx.model;

import java.io.Serializable;
import java.util.Date;
/**
 * 逆向工程生成的实体类
 * 本逆向工程生成的实体类不够严谨
 * 自己补充 有参 无参构造器 以及toString方法
 * 该类实现序列化
 */
public class Album implements Serializable {
    private Integer aid;

    private String aname;

    private String pic;

    private String company;

    private Date pdate;

    private String lang;

    public Album(Integer aid, String aname, String pic, String company, Date pdate, String lang) {
        this.aid = aid;
        this.aname = aname;
        this.pic = pic;
        this.company = company;
        this.pdate = pdate;
        this.lang = lang;
    }

    public Album() {
    }

    public Integer getAid() {
        return aid;
    }

    public void setAid(Integer aid) {
        this.aid = aid;
    }

    public String getAname() {
        return aname;
    }

    public void setAname(String aname) {
        this.aname = aname == null ? null : aname.trim();
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company == null ? null : company.trim();
    }

    public Date getPdate() {
        return pdate;
    }

    public void setPdate(Date pdate) {
        this.pdate = pdate;
    }

    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang = lang == null ? null : lang.trim();
    }

    @Override
    public String toString() {
        return "Album{" +
                "aid=" + aid +
                ", aname='" + aname + '\'' +
                ", pic='" + pic + '\'' +
                ", company='" + company + '\'' +
                ", pdate=" + pdate +
                ", lang='" + lang + '\'' +
                '}';
    }
}

基础的CURD即为基础的增删改查

创建Service层

创建impl包,创建MytpeServiceImpl实现类,和其接口 别的现在不需要创建

在service包中创建接口

在实现类中实现这些方法

我这里已经做到后边的内容了,所以这里放的是之前的截图,注意将重复部分删除

创建mybatis的全局配置文件

resources里面创建sqlMapConfig.xml

注册映射配置文件MtypeMapper.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/SongerMapper.xml"/>
        <mapper resource="mapper/AlbumMapper.xml"/>
        <mapper resource="mapper/MtypeMapper.xml"/>
        <mapper resource="mapper/SongMapper.xml"/>
    </mappers>
</configuration>

创建spring的配置文件

beans.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: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="cn.tx"></context:component-scan>

    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClass}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${uname}"></property>
        <property name="password" value="${pword}"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
    </bean>

    <bean id="mapperScan" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <property name="basePackage" value="cn.tx.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>
            <!--
                propagation="REQUIRED": 设置事务的传播行为。
                REQUIRED 表示如果当前线程中没有事务,就创建一个新事务;
                如果有,就加入当前事务
            -->
            <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"/>
            <!-- read-only="true": 表示该方法是只读的(适用于查询操作) -->
            <tx:method name="get" read-only="true"/>
            <tx:method name="select" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- AOP配置 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.tx.service..*.*(..))"></aop:advisor>
        <!--指定切点表达式,表示在哪些方法上应用事务通知。-->
    </aop:config>
</beans>

将MtypeServiceImpl交给spring去管理

创建测试整合

package cn.tx.test;

import cn.tx.model.Mtype;
import cn.tx.service.MtypeService;
import cn.tx.service.SongerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:beans.xml"})
public class MtypeTest {

    @Autowired
    MtypeService mtypeService;

    @Test
    public void getById(){
        Mtype mtype = mtypeService.selectByPrimaryKey(1);
        System.out.println(mtype);
    }
}

通过业务层调用持久层,持久层调用对应的sql语句

输出结果

5.公共的代码抽取

数据库中的表的基础增删改查大部分是重复的,可以提取这些公共的代码创建一个实现类,以减少代码的重复,需要使用直接继承。

1.创建baseDao

持久层的向上提取

提取公用的Base持久层接口

基础CURD

泛型:

  • T传入的参数
  • Q用来分页查询的参数
package cn.tx.dao;

import java.util.List;

/**
 * 持久层的向上提取
 * 提取公用的Base持久层接口
 * 基础CURD
 * @param <Q>
 * @param <T>
 */
public interface BaseDao<Q,T> {
    /**
     * 保存数据
     * @param t
     */
    public void insert(T t);

    /**
     * 根据主键查询对象
     * @param id
     * @return
     */
    public T selectByPrimaryKey(Integer id);

    /**
     * 根据主键删除数据
     * @param id
     */
    public void deleteByPrimaryKey(Integer id);

    /**
     * 修改数据
     * @param t
     */
    public void updateByPrimaryKeySelective(T t);

    /**
     * 查询所有的记录
     * @return
     */
    public List<T> selectObjectAll();

    /**
     * 根据查询条件来查询数据
     * @param q
     * @return
     */
    public List<T> selectObjectByCondition(Q q);

    /**
     * 根据查询条件来查询符合条件的记录数
     * @param q
     * @return
     */
    public int selectObjectByConditionCount(Q q);

}

让mapper接口直接继承公共dao接口

package cn.tx.dao;

 import cn.tx.model.Mtype;
 import cn.tx.query.MtypeQuery;

/**
 * 逆向工程生成的持久层接口
 * 基础的CURD接口(增删改查)
 * 单表的查询
 */
  public interface MtypeMapper extends BaseDao<MtypeQuery, Mtype>{

  }

2.创建公共的Service接口

package cn.tx.service;

import java.util.List;

/**
 * 业务层的向上提取
 * 提取公用的Base业务层接口
 * 基础CURD
 * @param <Q>
 * @param <T>
 */
public interface BaseService<Q,T> {

    /**
     * 保存数据
     * @param t
     */
    public void insert(T t);

    /**
     * 根据主键查询对象
     * @param id
     * @return
     */
    public T selectByPrimaryKey(Integer id);

    /**
     * 根据主键删除数据
     * @param id
     */
    public void deleteByPrimaryKey(Integer id);

    /**
     * 修改数据
     * @param t
     */
    public void updateByPrimaryKeySelective(T t);

    /**
     * 查询所有的记录
     * @return
     */
    public List<T> selectObjectAll();

}

让实现类的接口继承公共接口

package cn.tx.service;

import cn.tx.model.Mtype;
import cn.tx.query.MtypeQuery;

/**
 * 流派模块的业务层接口
 * 逆向工程不能完成
 * 自己创建 补上
 */
public interface MtypeService extends BaseService<MtypeQuery, Mtype>{

}

3.创建公共的Service接口实现类

protected访问修饰符

protected的意思 同包下可以访问

package cn.tx.service.impl;

import cn.tx.dao.BaseDao;
import cn.tx.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务层实现类的向上提取
 * 提取公用的Base业务层接口的实现
 * 基础CURD
 * @param <Q>
 * @param <T>
 */
@Service
public class BaseServiceImpl<Q,T> implements BaseService<Q,T> {

    /**
     * 如何注入BaseDao的值
     * 可以支持两次注入 但是不好
     * 选择利用java基础的权限修饰符
     * 以及set方法注入的形式改成一次注入
     */
    //protected 同一个包下可以访问
    protected BaseDao<Q,T> baseDao;


    @Override
    public void insert(T t) {
        baseDao.insert(t);
    }

    @Override
    public T selectByPrimaryKey(Integer id) {
        return baseDao.selectByPrimaryKey(id);
    }

    @Override
    public void deleteByPrimaryKey(Integer id) {
        baseDao.deleteByPrimaryKey(id);
    }

    @Override
    public void updateByPrimaryKeySelective(T t) {
        baseDao.updateByPrimaryKeySelective(t);
    }

    @Override
    public List<T> selectObjectAll() {
        return baseDao.selectObjectAll();
    }
}

通过 @Autowiredsetter 方法注入,MtypeMapper 被注入到 BaseServiceImpl 中的baseDao 成员变量。

package cn.tx.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tx.dao.MtypeMapper;
import cn.tx.model.Mtype;
import cn.tx.query.MtypeQuery;
import cn.tx.service.MtypeService;

/**
 * 流派模块的业务层实现类
 * 逆向工程不能完成
 * 自己创建 补上
 */
@Service
public class MtypeServiceImpl extends BaseServiceImpl<MtypeQuery, Mtype> implements MtypeService {


   private MtypeMapper mtypeMapper;

   /**
    * 通过set方法给属性注入值
    * @param mtypeMapper
    */
   @Autowired
   public void setBrandDao(MtypeMapper mtypeMapper) {
      this.mtypeMapper = mtypeMapper;
      this.baseDao = mtypeMapper;
   }

}

6.代码生成器

提取了公用代码之后,具体的mapper接口,实现类接口,实现类中的代码数据很少且大致相同

在src/test/resources资源包下创建模板文件

1.创建模板

1.DemoMapper

package cn.tx.dao;

 import cn.tx.model.Demo;
 import cn.tx.query.DemoQuery;

/**
 * 逆向工程生成的持久层接口
 * 基础的CURD接口(增删改查)
 * 单表的查询
 */
public interface DemoMapper extends BaseDao<DemoQuery, Demo>{
    
}

2.DemoQuery

package cn.tx.query;

import cn.tx.model.Demo;

public class DemoQuery extends Demo {

}

3. DemoService

package cn.tx.service;

import cn.tx.model.Demo;
import cn.tx.query.DemoQuery;
/**
 * 流派模块的业务层实现类
 * 逆向工程不能完成
 * 自己创建 补上
 */
public interface DemoService extends BaseService<DemoQuery, Demo>{

}

4. DemoServiceImpl

package cn.tx.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tx.dao.DemoMapper;
import cn.tx.model.Demo;
import cn.tx.query.DemoQuery;
import cn.tx.service.DemoService;
/**
 * 流派模块的业务层实现类
 * 逆向工程不能完成
 * 自己创建 补上
 */
@Service
public class DemoServiceImpl extends BaseServiceImpl<DemoQuery, Demo> implements
      DemoService {


   private DemoMapper demoMapper;

   @Autowired
   public void setBrandDao(DemoMapper demoMapper) {
      this.demoMapper = demoMapper;
      this.baseDao = demoMapper;
   }

}

7.代码生成器的工具类

package cn.tx.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * 代码生成器的工具类
 * 生成模板所需要的内容
 * 按照一定格式快速生成一些类  基础内容
 * java基础IO流的读写功能
 */
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{

        //创建文件输入流
        BufferedReader br = new BufferedReader(new FileReader("ham-core/src/test/resources/tpl/DemoQuery.tpl"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("ham-core/src/main/java/cn/tx/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{

        //创建文件输入流
        BufferedReader br = new BufferedReader(new FileReader("ham-core/src/test/resources/tpl/DemoMapper.tpl"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("ham-core/src/main/java/cn/tx/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("ham-core/src/test/resources/tpl/DemoService.tpl"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("ham-core/src/main/java/cn/tx/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("ham-core/src/test/resources/tpl/DemoServiceImpl.tpl"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("ham-core/src/main/java/cn/tx/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删除,把model补全,再使用代码生成器,将dao、service接口和service实现类生成,有特殊功能就在其service接口中添加