idea使用maven整合ssm框架

本文为学习笔记,直接复制粘贴了网上大量资源,参考内容以下给出地址链接,侵删。

参考博客:

idea中搭建基于maven的ssm整合框架

解决idea新建maven项目时一直loading问题

maven中GroupID 和ArtifactID怎么写

Spring MVC welcome-file-list 问题

Mybatis-mybatis自动生成代码提示"Cannot obtain primary key information from ..."解决方案

使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件(转)

1.利用maven创建web项目

file->new->new project,选择maven。

这里可能会遇到archetype一直加载的问题。原因:idea一直读自己的配置里缓存导致的。

archetype一直加载的问题解决如下:
option 1:

打开:Setting---->Build Tools → Maven → Importing

VM options for importer 的值改为 -Xmx1024m。

option 2:

C:\Users\Administrator.IntelliJIdea2016.1\system\Maven(或者C:\Users\hc001.IntelliJIdea2016.1\system\Maven,总之在C盘找到.IntelliJIdea2016.1缓存) ,将Maven文件里面清空,然后重启idea。(这种方法我没有测试

解决之后,勾选crete from archetype,并选择如图所示的archetype:

选择next,填写GroupId和ArtifactId,GroupID 是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构。 比如源文件java包下java包结构是com.mycompanyname.mygroupname,mygroupname下一级目录为项目名,那么GroupId就填com.mycompanyname.mygroupname,而ArtifactId一般填写项目名。

填写project name 和 project location,点击finish。

finish

建完项目后,idea会自动导入基本的项目结构,这时注意idea右下角弹窗提示,允许idea自动导入。导入后的项目基本结构如图:

2.创建所需的目录和文件

我一般使用的目录结构如图,文件详细内容和配置代码后面会给出。创建src/main下面的java文件后,选中java,右键mark directory as ,选择java root。

3.配置文件

配置文件中注意注释,有的注释指出了应该修改成你自己的一些东西。

pom.xml

首先把引入jar包,由于项目是通过maven管理的,所以只要添加pom文件中的dependency。

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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>
    <packaging>war</packaging>

    <name>discuss</name>
    <groupId>cn.edu.jlu</groupId>
    <artifactId>disscus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.7</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8888</port>
                            <maxIdleTime>30000</maxIdleTime>
                        </connector>
                    </connectors>
                    <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}
                    </webAppSourceDirectory>
                    <contextPath>/</contextPath>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>

</project>

添加spring配置文件
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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.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">



  <!--自定义拦截器-->
  <mvc:interceptors>
    <mvc:interceptor>
      <mvc:mapping path="/*.do"/>
      <!--需要对应自己的拦截器的地址-->
      <bean class="discuss.interceptor.MyInterceptor"></bean>
    </mvc:interceptor>
  </mvc:interceptors>

</beans>
applicationContext-springmvc.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: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="discuss.*"/>

    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>
    <!-- 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <bean name="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON转换器 -->
            </list>
        </property>
    </bean>
    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="1"/>
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--这里是对静态资源的映射-->
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/img/**" location="/img/" />

    <!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxUploadSize" value="32505856"/>
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="4096"/>
    </bean>
</beans>
applicationContext-mybatis.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">


    <context:component-scan base-package="discuss.service" use-default-filters="false"/>
    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc/jdbc.properties"/>


    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>

    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 扫描model包 使用别名 -->
        <property name="typeAliasesPackage" value="discuss.entity"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <property name="configurationProperties">
            <props>
                <prop key="mapUnderscoreToCamelCase">true</prop>
            </props>
        </property>
    </bean>

    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="discuss.dao"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

</beans>
jdbc.properties

url,username,password需手动修改成自己的数据库

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/discuss?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
#最大连接数
c3p0.maxPoolSize=30000
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">

  <!--首页,这里并没有实现,实现请看参考链接-->
  <welcome-file-list>
    <welcome-file>jsp/index.jsp</welcome-file>
  </welcome-file-list>

  <!--springMVC拦截器-->
  <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/applicationContext*.xml</param-value>
      <!--  <param-value>classpath:bean/applicationContext.xml</param-value>-->
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
    <!--springMVC拦截的地址格式-->
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <context-param>
    <!--springmvc的配置文件-->
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext*.xml</param-value>
  </context-param>


  <!-- 编码过滤器 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- spring监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 防止spring内存溢出监听器,比如quartz -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
</web-app>

4.编写一个测试类

创建数据库

测试用sql脚本,创建测试用的user表和插入一条数据。

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `email` varchar(255) NOT NULL COMMENT '用户邮箱',
  `password` varchar(255) NOT NULL COMMENT '用户密码',
  `username` varchar(255) NOT NULL COMMENT '用户昵称',
  `role` varchar(255) NOT NULL COMMENT '用户身份',
  `status` int(1) NOT NULL COMMENT '用户状态',
  `regTime` datetime NOT NULL COMMENT '注册时间',
  `regIp` varchar(255) NOT NULL COMMENT '注册IP',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'xxx', 'xxxxx', 'xxxxx', 'root', '0', '2017-03-28 09:40:31', '127.0.0.1');
SET FOREIGN_KEY_CHECKS=1;
mapper映射文件

在mapper目录下创建测试用的user.xml,建立数据库表和实体user类的映射关系。

user.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 设置为IUserDao接口方法提供sql语句配置 -->
<mapper namespace="discuss.dao.IUserDao">
    <resultMap id="userList" type="discuss.entity.User">

        <id column="id" property="id"/>
        <id column="email" property="email"/>
        <id column="password" property="password"/>
        <id column="username" property="username"/>
        <id column="role" property="role"/>
        <id column="status" property="status"/>
        <id column="regTime" property="regTime"/>
        <id column="regIp" property="regIp"/>
    </resultMap>
    <select id="getAllUser" resultMap="userList">
        SELECT * FROM user
    </select>

</mapper>
IUserDao

在dao中创建一个接口,代码如下

package discuss.dao;

import discuss.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface IUserDao {
    public List<User> getAllUser();
}
IUserService和UserServiceImpl

在service目录下创建接口IUserService和实现类UserServiceImpl。

package discuss.service;

public interface IUserService {
}

package discuss.service;

import discuss.dao.IUserDao;
import discuss.entity.User;
import org.springframework.stereotype.Service;

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

@Service("userService")
public class UserServiceImpl implements IUserService{
    @Resource
    private IUserDao userDao;
    public List<User> getUser() {
        return userDao.getAllUser();
    }
}

UserController

在controller目录下创建UserController类。

package discuss.controller;

import discuss.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    public UserServiceImpl userService;
    @RequestMapping("info")
    @ResponseBody
    public List userInfor(){
        System.out.println("----------------------------------------------");
        System.out.println( userService.getUser().size());
        return userService.getUser();
    }
}

User

在entity中创建实体类User。

package discuss.entity;

import java.sql.Timestamp;

public class User {
    private int id;
    private String email;
    private String password;
    private String username;
    private String role;
    private int status;
    private Timestamp regTime;
    private String regIp;

    public int getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Timestamp getRegTime() {
        return regTime;
    }

    public void setRegTime(Timestamp regTime) {
        this.regTime = regTime;
    }

    public String getRegIp() {
        return regIp;
    }

    public void setRegIp(String regIp) {
        this.regIp = regIp;
    }
}

5.部署项目

添加tomcat服务器

点击右上角符号:

然后点击绿色的 ‘+’ 号,选择tomcat。

配置tomcat,确定计算机上已经安装了tomcat。

name 随便取一个。

Application server要点击Configure找到tomcat的安装目录。

端口默认即可。

点击右下角Fix。

部署artifact
访问

启动tomcat,访问http://localhost:8080/user/info.do

访问路径可以在controller中通过注解配置。

成功访问界面:

​ Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件。

1、准备要自动生成的数据库表。

数据库为discuss
users表

CREATE TABLE `users` (
`user_id`  int NOT NULL AUTO_INCREMENT ,
`user_account`  varchar(30) NOT NULL ,
`user_password`  char(32) NOT NULL ,
`user_nickname`  varchar(30) NOT NULL ,
`user_email`  varchar(50) NOT NULL ,
`user_avatar`  varchar(30) NOT NULL DEFAULT 'default.jpg' ,
PRIMARY KEY (`user_id`)
)
;

plates表

CREATE TABLE `plates` (
`plate_id`  int NOT NULL AUTO_INCREMENT ,
`plate_name`  varchar(30) NOT NULL ,
`plate_profile`  text NULL ,
`plate_announcement`  text NULL ,
PRIMARY KEY (`plate_id`)
)
;


themes表

CREATE TABLE `themes` (
`theme_id`  int NOT NULL AUTO_INCREMENT ,
`theme_name`  varchar(30) NOT NULL ,
PRIMARY KEY (`theme_id`)
)
;

posts表

CREATE TABLE `posts` (
`post_id`  int NOT NULL AUTO_INCREMENT ,
`post _title`  varchar(30) NOT NULL ,
`post_author`  varchar(30) NOT NULL ,
`user_id`  int NOT NULL ,
`post_plate`  varchar(30) NOT NULL ,
`plate_id`  int NOT NULL ,
`post_theme`  varchar(30) NOT NULL ,
`theme_id`  int NOT NULL ,
`post_content`  text NOT NULL ,
`post_release_time`  datetime NULL ,
PRIMARY KEY (`post_id`)
)
;

admins

CREATE TABLE `admins` (
`admin_id`  int NOT NULL AUTO_INCREMENT ,
`admin_account`  varchar(30) NOT NULL ,
`admin_nickname`  varchar(30) NOT NULL ,
`admin_password`  char(32) NOT NULL ,
`admin_plate`  varchar(30) NOT NULL ,
`plate_id`  int NOT NULL ,
PRIMARY KEY (`admin_id`)
)
;


comments

CREATE TABLE `comments` (
`comment_id`  int NOT NULL AUTO_INCREMENT ,
`comment_from`  varchar(30) NOT NULL ,
`user_id`  int NOT NULL ,
`commment_time`  datetime NOT NULL ,
`comment_content`  text NOT NULL ,
`post_id`  int NOT NULL ,
PRIMARY KEY (`comment_id`)
)
;


​ 2、准备jar包

​ 关于Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases

​ 由于我使用的是Mysql数据库,这里需要在准备一个连接mysql数据库的驱动jar包,这个包可以在http://mvnrepository.com/中搜索下载,选择自己需要的版本。

​ 新建文件夹src。(生成的文件将在此目录下)

​ 同时,需要一个配置文件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>
    <!--数据库驱动,要对应自己的mysql-connector—java包的版本-->
    <classPathEntry location="mysql-connector-java-6.0.6-bin.jar"/>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL= connectionURL="jdbc:mysql://127.0.0.1:3306/discuss?nullCatalogMeansCurrent=true&amp;serverTimezone=UTC&amp;userUnicode=true&amp;characterEncoding=UTF8&amp;useSSL=false" userId="root"
                        password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成类的存放位置在src目录下,我的具体包为cn.edu.jlu.discuss-->
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="cn.edu.jlu.discuss.model" targetProject="src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="cn.edu.jlu.discuss.mapping" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.edu.jlu.discuss.dao" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--数据库中的表生成对应的类-->
        <table tableName="users" domainObjectName="User">
            <!--设置主键-->
            <generatedKey column="user_id" sqlStatement="MYSQL" identity="true"/>
        </table>
        <table tableName="admins" domainObjectName="Admin">
            <generatedKey column="admin_id" sqlStatement="MYSQL" identity="true"/>
        </table>
        <table tableName="comments" domainObjectName="Comment">
            <generatedKey column="comment_id" sqlStatement="MYSQL" identity="true"/>
        </table>
        <table tableName="plates" domainObjectName="Plate">
            <generatedKey column="plate_id" sqlStatement="MYSQL" identity="true"/>
        </table>
        <table tableName="posts" domainObjectName="Post">
            <generatedKey column="post_id" sqlStatement="MYSQL" identity="true"/>
        </table>
        <table tableName="themes" domainObjectName="Theme">
            <generatedKey column="theme_id" sqlStatement="MYSQL" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

然后在目录\mybatis-generator-core-1.3.6\lib地址栏中输入cmd,回车。

在弹出的控制台中输入命名行:(注意自己的jar版本)

java -jar mybatis-generator-core-1.3.6.jar -configfile generatorConfig.xml -overwrite

由于使用了高版本mysql-connector-java,有时会出现各种各样的问题,比如需要手动设置时区,手动指定ssh等等问题,这时需要添加修改connectionURL="jdbc:mysql://127.0.0.1:3306/discuss?nullCatalogMeansCurrent=true&serverTimezone=UTC&userUnicode=true&characterEncoding=UTF8&useSSL=false"字段,特别的,主键可能会无法获取,这是在url字段要加上?nullCatalogMeansCurrent=true

生成的文件如下:

posted @ 2018-05-21 10:36  苏小五  阅读(4605)  评论(0编辑  收藏  举报