一、配置环境
-
配置jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///easybuy?serverTimezone=UTC&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
#最大连接池数量 初始化建立物理连接的个数 获取连接时最长的等待时间 最小连接池数量 maxIdle已经弃用
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
maxIdle:15
-
配置log4j.properties
log4j.rootLogger=debug,stdout,logfile
#console output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.stdout.PatternLayout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}<-->%F<-->%p<-->%m%n
#file output
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=D:/logs/log.log
log4j.appender.logfile.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile.PatternLayout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}<-->%F<-->%p<-->%m%n
#mybatis log
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
-
编写映射文件(XxxxMapper.xml)
- 指定namespace
- 给实体起别名
- 编写sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.Supplier1Mapper">
<!--查所有-->
<select id="getAll" resultType="Supplier1" parameterType="Supplier1">
SELECT * FROM supplier1
</select>
<insert id="addS" parameterType="Supplier1">
INSERT INTO `supplier1` (`id`, `supCode`, `supName`, `supDesc`, `supContact`)
VALUES (#{id}, #{supCode}, #{supName}, #{supDesc}, #{supContact});
</insert>
<delete id="deleteS" parameterType="java.lang.Integer">
delete from supplier1 where id=#{id}
</delete>
<update id="updateS" parameterType="Supplier1">
UPDATE `supplier1`
<trim prefix="SET" suffixOverrides="," >
<if test="supCode!=null">
supCode=#{supCode},
</if>
<if test="supName!=null">
supName=#{supName},
</if>
<if test="supDesc!=null">
supDesc=#{supDesc},
</if>
<if test="supContact!=null">
supContact=#{supContact}
</if>
</trim>
WHERE `id` = #{id};
</update>
<select id="getById" resultType="Supplier1" parameterType="java.lang.Integer">
SELECT * FROM supplier1 where id=#{id}
</select>
</mapper>
-
编写核心文件(mybatis-config.xml)
- 用定义别名
- 配置分页助手插件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置懒加载-->
<!--<settings>
<setting name="cacheEnable" value="true"></setting>
</settings>-->
<!--设置 日志 缓存 自动匹配-->
<settings>
<setting name="autoMappingBehavior" value="FULL" />
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--简写实体类的名字 -->
<typeAliases>
<!--<typeAlias alias="TSys" type="pojo.TSysUser"/>-->
<!--自动匹配实体类 名字-->
<package name="pojo"/>
</typeAliases>
<mappers>
<mapper resource="mapper/Supplier1Mapper.xml"/>
</mappers>
</configuration>
-
配置spring(applicationContext.xml)
- 组件扫描 service和mapper
- 加载properties文件
- 配置数据源信息
- 配置sessionFactory
- 加载数据源信息
- 加载mybatis核心文件
- 扫描mapper所在包 为mapper创建实现类
- 声明事务控制
- 平台事务管理器
- 配置事务增强
- 事务的aop织入
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--注解实现依赖注入 扫描包里面的注解-->
<context:component-scan base-package="dao,service"/>
<!-- 加载db.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 创建数据源 JNDI获取数据源(使用dbcp连接池)-->
<!--com.alibaba.druid.pool.DruidDataSource-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxWait" value="${maxWait}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxIdle" value="${maxIdle}"/>
</bean>
<!-- 创建SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载数据源 -->
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4创建Mapper扫描器 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 4.1 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 编写通知:对事务进行增强(通知),需要编写对切点和具体执行事务细节
属性:id:唯一标识
transaction-manager:指定事务管理器 id,默认值就是 transactionManager
-->
<tx:advice id="advice" transaction-manager="txManager">
<tx:attributes>
<!-- 事务配置
属性:name:对哪些方法起作用,例如:insert* 表示所有以 insert 开头的方法名称。
一般只需要对增、删、改方法添加事务
rollback-for:指定需要进行事务回滚的异常类,默认是 uncheck 异常
其它属性一般默认即可
-->
<tx:method name="insert*" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" rollback-for="java.lang.Exception"/>
<tx:method name="update*" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<!-- 编写 aop,对目标生成代理,进行事务的通知 -->
<aop:config>
<!-- 配置切点表达式 -->
<aop:pointcut id="txPointcut" expression="execution (* service.impl.*ServiceImpl.*(..))"/>
<!-- 将切点和事务的通知整合 -->
<aop:advisor advice-ref="advice" pointcut-ref="txPointcut"/>
</aop:config>
<!-- 开启事务的注解支持
transaction-manager 属性:指定事务管理器 id,默认值就是 transactionManager-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
-
配置spring-mvc.xml
- 组件扫描 controller
- 配置 mvc注解驱动
- 配置内部资源视图解析器
- 开放静态资源访问权限
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置controller-->
<!--<bean id="/indexController" class="controller.IndexController"></bean>
<bean id="/hello" class="controller.HelloController"></bean>-->
<!--基于注解实现mvc-->
<context:component-scan base-package="controller"/>
<!--自动注册 controller 里面 类的映射器和适配器-->
<mvc:annotation-driven/>
<!--json乱码配置问题-->
<!-- 注解驱动,直接利用springmvc中的注解实现json与object之间的互相转换 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="utf-8"></constructor-arg>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"></property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--配置视图-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/EasybuyUser/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
-
配置web.xml
- spring监听器
- springmvc的前端控制器
- 乱码过滤器
<?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_4_0.xsd"
version="4.0">
<!--servlet servlet-mapping-->
<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*:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--加载ApplicationContext.xml-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!--加载spring配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc的乱码过滤器-->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
二、代码编写
(首先要清楚Controller层是实现后端与前端页面的跳转,Controller调用service层,service层调用Dao层,UserDao.xml文件实现sql语句的编写)
实体类
package pojo;
import lombok.Data;
@Data
public class Supplier1 {
private long id;
private String supCode;//供应商编码
private String supName;//供应商名称
private String supDesc;//供应商详细描述
private String supContact;//供应商联系人
}
Supplier1Mapper接口
package dao;
import org.springframework.stereotype.Repository;
import pojo.Supplier1;
import java.util.List;
/**
* @ClassName Supplier1Mapper
* @Description TODO
* @Author wangJiaXin
* @Date 2023-08-17 16:55
* @Version 1.0
*/
@Repository
public interface Supplier1Mapper {
/**
* 查所有
* @return
*/
List<Supplier1> getAll();
/**
* 新增
* @param supplier1
* @return
*/
int addS(Supplier1 supplier1);
/**
* 删除
* @param id
* @return
*/
int deleteS(Integer id);
/**
* 修改
* @param supplier1
* @return
*/
int updateS(Supplier1 supplier1);
/**
* 根据编号查询
* @param id
* @return
*/
Supplier1 getById(Integer id);
}
Supplier1Service接口
package service;
import pojo.Supplier1;
import java.util.List;
/**
* @ClassName Supplier1Service
* @Description TODO
* @Author wangJiaXin
* @Date 2023-08-17 16:57
* @Version 1.0
*/
public interface Supplier1Service {
/**
* 查所有
* @return
*/
List<Supplier1> getAll();
/**
* 新增
* @param supplier1
* @return
*/
int addS(Supplier1 supplier1);
/**
* 删除
* @param id
* @return
*/
int deleteS(Integer id);
/**
* 修改
* @param supplier1
* @return
*/
int updateS(Supplier1 supplier1);
/**
* 根据编号查询
* @param id
* @return
*/
Supplier1 getById(Integer id);
}
Supplier1ServiceImpl
package service.impl;
import dao.Supplier1Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.Supplier1;
import service.Supplier1Service;
import java.util.List;
/**
* @ClassName Supplier1ServiceImpl
* @Description TODO
* @Author wangJiaXin
* @Date 2023-08-17 16:58
* @Version 1.0
*/
@Service("supplier1Service")
public class Supplier1ServiceImpl implements Supplier1Service {
@Autowired
private Supplier1Mapper mapper;
@Override
public List<Supplier1> getAll() {
return mapper.getAll();
}
@Override
public int addS(Supplier1 supplier1) {
return mapper.addS(supplier1);
}
@Override
public int deleteS(Integer id) {
return mapper.deleteS(id);
}
@Override
public int updateS(Supplier1 supplier1) {
return mapper.updateS(supplier1);
}
@Override
public Supplier1 getById(Integer id) {
return mapper.getById(id);
}
}
Supplier1Controller中代码
package controller;
import dao.Supplier1Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import pojo.Supplier1;
import java.util.List;
/**
* @ClassName SupplierController
* @Description TODO
* @Author wangJiaXin
* @Date 2023-08-22 16:17
* @Version 1.0
*/
@Controller
@RequestMapping("/supplier1")
public class Supplier1Controller {
@Autowired
private Supplier1Mapper supplier1Mapper;
@RequestMapping("/getAll")
public ModelAndView getAll(ModelAndView modelAndView){
List<Supplier1> all = supplier1Mapper.getAll();
modelAndView.addObject("list",all);
modelAndView.setViewName("supplier_index");
return modelAndView;
}
@RequestMapping("/inserSupplier")
public String inserSupplier(Supplier1 supplier1){
int i = supplier1Mapper.addS(supplier1);
if (i>0){
return "redirect:/supplier1/getAll";
}
return "redirect:/supplier1/getAll";
}
@RequestMapping("/updateSupplier")
public String updateSupplier(Supplier1 supplier1){
int i = supplier1Mapper.updateS(supplier1);
if (i>0){
return "redirect:/supplier1/getAll";
}
return "redirect:/supplier1/getAll";
}
@RequestMapping("/deleteSupplier")
public String deleteSupplier(Integer id){
int i = supplier1Mapper.deleteS(id);
if (i>0){
return "redirect:/supplier1/getAll";
}
return "redirect:/supplier1/getAll";
}
@RequestMapping("/selectById")
public ModelAndView selectById(ModelAndView modelAndView,Integer id){
Supplier1 byId = supplier1Mapper.getById(id);
if (byId!=null){
modelAndView.addObject("byId",byId);
modelAndView.setViewName("update");
return modelAndView;
}
modelAndView.setViewName("404");
return modelAndView;
}
}