import Changes
的jar(这里会自动加载构建maven项目的jar包)附:这里,maven就算是整合完了,需要下载什么jar包,以及其所依赖的其他所有jar包,maven都会帮你管理和下载。
maven平台(需要什么jar包直接搜):http://mvnrepository.com
例:我需要mysql的jdbc连接数据库的jar包,在maven平台搜索mysql,找到并复制下方箭头的代码粘贴到项目的pom.xml文件中,如图:
粘贴 到项目配置文件pom.xml
中的dependencies标签
中,选择Import Changes
引入jar包
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>3.2.13.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>3.2.13.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>3.2.13.RELEASEversion>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.11version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.9version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>3.2.13.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>3.2.13.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>jsptagsgroupId>
<artifactId>pager-taglibartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.32version>
dependency>
<dependency>
<groupId>org.codehaus.jacksongroupId>
<artifactId>jackson-core-aslartifactId>
<version>1.9.12version>
dependency>
<dependency>
<groupId>org.codehaus.jacksongroupId>
<artifactId>jackson-mapper-aslartifactId>
<version>1.9.12version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.2version>
dependency>
快捷键:Ctrl+Alt+Shift+S
打开Project Structure
项目配置Modules
,Soruces
,在src和main下右键新建文件夹说明:
src->main->java下新建package cn,再新建package test,这两个对应我们刚开始的groupid
main文件夹目录下:
- java.cn.test包下新建四个包:
controller包用来放前台url映射文件,mapper用来放与数据库的接口文件,pojo用来放实体类文件,service用来放自己定义的接口,util用来放我们的工具类。- resourecs文件夹下:
applicationContext.xml是spring配置文件
新建sqlmap文件夹,里面放实体与数据库的映射文件
generatorConfig.xml和generator.properties是mybatis逆向工程的配置文件-用于生成实体类等
database.properties是数据库相关信息
log4j.properties是日志配置文件
mybatis-config.xml是mybatis配置文件
spring-servlet.xml是springMVC配置文件- webapp下:
新建statics文件夹,用来放前端资源
web-inf下新建jsp文件夹,用来存放jsp页面文件
3.2 resoures配置的全部源码:
applicationContext.xml是spring配置文件(cn.test.**路径名要和你的命名相同)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
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-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:property-placeholder
location="classpath:database.properties"/>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="maxWait" value="${maxWait}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="removeAbandoned" value="${removeAbandoned}"/>
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation"
value="classpath:mybatis-config.xml"/>
<property name="mapperLocations">
<list>
<value>classpath:sqlmap/*.xmlvalue>
list>
property>
<property name="typeAliasesPackage" value="cn.test.pojo"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="cn.test.mapper"/>
bean>
<context:component-scan base-package="cn.test.service"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="search*" read-only="true"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pointcut"
expression="execution(* cn.test.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
aop:config>
beans>
新建sqlmap文件夹,里面放实体与数据库的映射文件
在sqlmap文件夹下新建UserMapper,放入文件头
<mapper namespace="cn.test.mapper.UserMapper">
mapper>
这里所对应的的接口为java.cn.test.mapper中的同名UserMapper.java,
这里暂时不用新建,后面我们会用【Mybatis逆向工程】自动新建实体类,再对应mapper:
generatorConfig.xml和generator.properties是mybatis逆向工程的配置文件-用于生成实体类等
后面给出~~~
database.properties是数据库相关信息(我的mysql版本为8.0)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
user=root
password=wy123456
minIdle=45
maxIdle=50
initialSize=5
maxActive=100
maxWait=100
removeAbandonedTimeout=180
removeAbandoned=true
log4j.properties是日志配置文件
log4j.rootLogger=debug,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms=debug
log4j.logger.org.apache.ibatis=debug
log4j.logger.org.mybatis.spring=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
######################################################################################
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=debug
log4j.appender.CONSOLE.DatePattern=yyyy-MM-dd
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
######################################################################################
# Rolling File \u6587\u4ef6\u5927\u5c0f\u5230\u8fbe\u6307\u5b9a\u5c3a\u5bf8\u7684\u65f6\u5019\u4ea7\u751f\u4e00\u4e2a\u65b0\u7684\u6587\u4ef6
######################################################################################
#log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.ROLLING_FILE.Threshold=INFO
#log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
#log4j.appender.ROLLING_FILE.Append=true
#log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
#log4j.appender.ROLLING_FILE.MaxBackupIndex=100
#log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
######################################################################################
# DailyRolling File \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=${SMBMS_C12_10.root}/logs/log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
#DWR \u65e5\u5fd7
#log4j.logger.org.directwebremoting = ERROR
#\u663e\u793aHibernate\u5360\u4f4d\u7b26\u7ed1\u5b9a\u503c\u53ca\u8fd4\u56de\u503c
#log4j.logger.org.hibernate.type=DEBUG,CONSOLE
#log4j.logger.org.springframework.transaction=DEBUG
#log4j.logger.org.hibernate=DEBUG
#log4j.logger.org.acegisecurity=DEBUG
#log4j.logger.org.apache.myfaces=TRACE
#log4j.logger.org.quartz=DEBUG
#log4j.logger.com.opensymphony=INFO
#log4j.logger.org.apache.struts2=DEBUG
log4j.logger.com.opensymphony.xwork2=debug
mybatis-config.xml是mybatis配置文件
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
settings>
configuration>
spring-servlet.xml是springMVC配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
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">
<context:component-scan base-package="cn.test.controller"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:resources mapping="/statics/**" location="/statics/"/>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">errorprop>
props>
property>
bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="5242880"/>
bean>
beans>
3.1 新建server:Edit Configuration
->新建Tomcat local
附:Server设置中:on frame换成update classes and resources,这样修改了jsp页面不用重启服务器,实现热部署,然后上面的tomcat我们要注意是自己本地的tomcat位置,没有的自己去下一个,接下来启动,看看行不行。
解决控制台中文乱码:
配置Java编译版本:eclipse,jre版本为1.8
在Tomcat配置中VM options
控制台加:-Dfile.encoding=UTF-8
控制台乱码问题解决:
实体类,sqlmapper文件等等很是麻烦,
通过逆向工程,可以自动帮我们联系数据库生成实体类及映射。
4.1src.main.resources下:
注:classPathEntry节点的location需要修改
<generatorConfiguration>
<properties resource="generator.properties"/>
<classPathEntry
location="C:\Users\CUNGU\.m2\repository\mysql\mysql-connector-java\8.0.11\mysql-connector-java-8.0.11.jar" />
<context id="context1">
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
commentGenerator>
<jdbcConnection driverClass="${driver}"
connectionURL="${url}"
userId="${user}"
password="${password}" />
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
javaTypeResolver>
<javaModelGenerator targetPackage="${modelPackage}"
targetProject="${modelProject}" />
<sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
<javaClientGenerator targetPackage="${mapperPackage}"
targetProject="${mapperProject}" type="XMLMAPPER" />
<table schema="" tableName="${table}" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/>
context>
generatorConfiguration>
找到项目目录下的jar包,找到mysql的jar包,点击copy path,将复制的路径,替换location的路径。
4.2 generator.properties文件:
这里面保存的是连接数据库的相关信息,是在使用mybatis-generator这个功能的时候用到的;
之前的database.properties是系统运行时用到的。
二者信息差不多,图方便的话,也可以将两个合并成一个文件,分开写的话,好实现可插拔。
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
user=root
password=wy123456
#entity 包名和 java目录
modelPackage=cn.test.pojo
modelProject=src/main/java
#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources
#mapper包名和 java目录
mapperPackage=cn.test.mapper
mapperProject=src/main/java
table=news
modelPackage是等会连接数据库自动生成的实体类保存的位置,sqlPackage是生成xml映射文件保存的位置,mapperPackage是生成数据库接口保存的位置,table是数据库里面的表的名字
4.3 打开我们的pom.xml文件:在第182行插入如下代码,用于使用mybatis-generator
,记得Import Changes
引入jar包
/*
Navicat Premium Data Transfer
Source Server : mysql
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 30/07/2019 17:28:06
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for news
-- ----------------------------
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`time` bigint(10) NOT NULL,
`author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`typeid` int(255) NOT NULL,
`content` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `type`(`typeid`) USING BTREE,
CONSTRAINT `news_ibfk_1` FOREIGN KEY (`typeid`) REFERENCES `type` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of news
-- ----------------------------
INSERT INTO `news` VALUES (2, '1', 10, '张三', 1, '新闻测试内容');
INSERT INTO `news` VALUES (3, 'mybatis逆向工程', 1564478202245, '李四', 1, '测试测试测试。。。。');
-- ----------------------------
-- Table structure for type
-- ----------------------------
DROP TABLE IF EXISTS `type`;
CREATE TABLE `type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of type
-- ----------------------------
INSERT INTO `type` VALUES (1, '原创');
SET FOREIGN_KEY_CHECKS = 1;
双击运行mybatis-generator:
这里因为mysql8.0版本问题,修改了一下配置,成功运行结果如下:
成功生成具体内容:
很多时候我们写完一段代码,想去验证他的正确性,并不一定需要去启动tomcat跑跑看或者debug,我们可以使用测试工具来验证,这儿配置junit测试。
打开newsmapper.java接口文件:
然后可以新建测试文件开始测试,将光标移到public interface NewsMapper后面,点击提示小电灯泡(或键盘上按下alt+enter键),接着create test
勾选你要进行测试的方法,点击ok,生成测试文件
会自动新建test/java/cn/test/mapper目录,并新建Test:
完整的测试内容:
package cn.test.mapper;
import cn.test.pojo.News;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class NewsMapperTest {
private ApplicationContext applicationContext;
@Autowired
private NewsMapper newsMapper;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");//加载spring配置文件
newsMapper = applicationContext.getBean(NewsMapper.class);//在这里导入要测试的
}
@Test
public void insertSelective() {
News news = new News();
news.setTitle("mybatis逆向工程");
news.setAuthor("李四");
news.setContent("测试测试测试。。。。");
news.setTime(System.currentTimeMillis());//这里是当前时间戳
news.setTypeid(1);
Integer result = newsMapper.insertSelective(news);
System.out.println(result);
assert (result == 1);
}
@Test
public void selectByPrimaryKey() {
News n = newsMapper.selectByPrimaryKey(3);
System.out.println("查询id为3的n.name = " + n.getAuthor());
}
}
大功告成!
虽然org.mybatis.generator能够大幅减轻Mybatis配置步骤,
但是对于较为复杂的sql还是得自己编写sql。
附:
1.Generator代码生成器-sql语句字符串拼接
SSM框架(七)Sping框架之SQL【Generator代码生成器】原理:https://blog.csdn.net/cungudafa/article/details/90637231
2.SpringMVC集成Mybatis主要流程演示,java、resources每部分作用讲解
SSM框架(六)SpringMVC-Spring集成【Mybatis搭建详述】附源码:(eclipse版)https://blog.csdn.net/cungudafa/article/details/90602754
3.逆向工程org.mybatis.generator自动生成流程参考
使用IDEA软件整合Maven+Spring+Spring MVC+Mybatis框架+SSM逆向工程+MySql数据库-及遇到的问题(持续记录):https://blog.csdn.net/lmq2582609/article/details/82878365
4.较为复杂的mapper接口中的方法解析
SSM学习(十)Mybatis反向自动生成工具原理:
https://blog.csdn.net/cungudafa/article/details/91335295