spring和mybatis的整合

首先创建数据库

CREATE TABLE car(
cid int PRIMARY key auto_increment,
cnumber VARCHAR(20),
type VARCHAR(20),
owner VARCHAR(20),
phone VARCHAR(20),
mark VARCHAR(20)
);

insert into car values (1,'豫A34G87','轿车','王文琦','13895647594','临时车');
insert into car values (2,"豫B38379","SUV","张玉梅","13687594623","月卡");
insert into car values (3,"豫CR9703","卡车","刘晓鹏","13975462146","年卡");
 select * from car where cid=2

 按创建结构如下,创建项目并导入所需要jar包

创建增强类Loger

package com.ye.advice;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//增强类
@Component
@Aspect
public class Loger {
    // 前置通知
    @Before("execution(int *..CarServicelmpl.*(..))")
    public void cherk(){
        System.out.println("前置通知...执行系统的权限验证");
    }
    // 后置通知
    @AfterReturning("execution(* *..CarServicelmpl.findAll(..))")
    public void logPrint(){
        System.out.println("后置通知...执行系统的权限验证");
    }
}

创建实体类Car

package com.ye.bean;

public class Car {
    private Integer cid;
    private String cnumber;
    private String type;
    private String owner;
    private String phone;
    private String mark;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCnumber() {
        return cnumber;
    }

    public void setCnumber(String cnumber) {
        this.cnumber = cnumber;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMark() {
        return mark;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }

    @Override
    public String toString() {
        return "Car{" +
                "cid=" + cid +
                ", cnumber='" + cnumber + '\'' +
                ", type='" + type + '\'' +
                ", owner='" + owner + '\'' +
                ", phone='" + phone + '\'' +
                ", mark='" + mark + '\'' +
                '}';
    }
}

创建dao层的接口及其mapper映射文件

接口类CarDao

package com.ye.dao;

import com.ye.bean.Car;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface CarDao {
    //全查
  List<Car> selectAll();
//增加
   int insert(Car car);
//根据id查
   Car selectcid(int cid);
//修改
   int update(Car car);
//删除
   int del(int cid);
}

配置mapper映射文件CarDao.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">
<mapper namespace="com.ye.dao.CarDao">
//全查
    <select id="selectAll" resultType="com.ye.bean.Car">
        select * from car
    </select>
//添加
    <insert id="insert" parameterType="com.ye.bean.Car">
        insert into car values (#{cid},#{cnumber},#{type},#{owner},#{phone},#{mark});
    </insert>
//根据id查询
    <select id="selectcid" parameterType="int" resultType="com.ye.bean.Car">
        select * from car where cid=#{cid}
    </select>
//修改
    <update id="update" parameterType="com.ye.bean.Car">
        update car
        <set>
            <if test="cnumber!=null and cnumber!=''">
                cnumber=#{cnumber},
            </if>
            <if test="type!=null and type!=''">
                type=#{type},
            </if>
            <if test="owner!=null and owner!=''">
                owner=#{owner},
            </if>
            <if test="phone!=null and phone!=''">
                phone=#{phone},
            </if>
            <if test="mark!=null and mark!=''">
                mark=#{mark},
            </if>
        </set>
        where cid=#{cid}
    </update>
//删除
    <delete id="del" parameterType="int">
        delete from car where cid=#{cid}
    </delete>
</mapper>

创建service接口及其实现类

接口类CarService

package com.ye.service;

import com.ye.bean.Car;

import java.util.List;

public interface CarService {

    List<Car> findAll();

    int findinsert(Car car);

    Car selectcid(int cid);

    int update(Car car);

    int del(int cid);
}

实现类CarServicelmpl

package com.ye.service.impl;

import com.ye.bean.Car;
import com.ye.dao.CarDao;
import com.ye.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CarServicelmpl implements CarService {
    @Autowired
    CarDao carDao;
    @Override
    public List<Car> findAll() {
        return carDao.selectAll();
    }

    @Override
    public int findinsert(Car car) {
        return carDao.insert(car);
    }

    @Override
    public Car selectcid(int cid) {
        return carDao.selectcid(cid);
    }

    @Override
    public int update(Car car) {
        return carDao.update(car);
    }

    @Override
    public int del(int cid) {
        return carDao.del(cid);
    }


}

Log4j.properties日志

Log4j由三个重要的组件构成:日志信息的优先级,日志信息的输出目的地,日志信息的输出格式。日志信息的优先级从高到低有ERROR、WARN、 INFO、DEBUG,分别用来指定这条日志信息的重要程度;日志信息的输出目的地指定了日志将打印到控制台还是文件中;而输出格式则控制了日志信息的显 示内容。

log4j.rootLogger=TRACE,stdout  

log4j.appender.stdout=org.apache.log4j.ConsoleAppender   
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout   


log4j.appender.logfile=org.apache.log4j.FileAppender   
log4j.appender.logfile.File=wocao.log   
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout   
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n   
log4j.logger.mapperNS =TRACE

log4j.logger.com.mybatis=DEBUG  
log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG   
log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG   
log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=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  

log4j.logger.org.springframework=error 
log4j.logger.org.apache=ERROR  
log4j.logger.org.mybatis=DEBUG 

 效果

 创建mybatis配置文件配置环境信息

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置环境信息===就是配置连接数据库的参数
default:指定配置的环境信息的id,表示默认连接该环境
-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>

</configuration>

创建spring配置文件

<?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"
       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">

    <!--扫描Component及同名注解-->
    <context:component-scan base-package="com.ye"/>

    <aop:aspectj-autoproxy/>
    <!--1.配置spring管理连接数库的数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!-- 2.使用上面的数据源配置mybatis的SqlSessionFactory对象交给IDC容器管理,有了SqlSessionFactory-->
    <!--   对象就可以创建SqlSession对象,有了SqlSession对象就有了代理对象,创建什么代理对象?用下面进行鉴定义-->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 3.配置mapper扫描器,确定需要创建的代理对象   -->
    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ye.dao"/>

    </bean>

</beans>

测试类

package com.ye.servlet;

import com.ye.bean.Car;
import com.ye.service.CarService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class CarDaoTest {
    @Test
    public void selectAll(){
//        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext("spring.xml");
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        CarService car = context.getBean(CarService.class);
        List<Car> all = car.findAll();
        for (Car car1 : all) {
            System.out.println(car1);
        }
    }
    @Test
    public void insert(){
//        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext("spring.xml");
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        CarService car = context.getBean(CarService.class);
        Car car1=new Car();
        car1.setCid(7);
        car1.setCnumber("京A666");
        car1.setType("跑车");
        car1.setOwner("小明");
        car1.setPhone("1663667666");
        car1.setMark("终身VIP");
        int findinsert = car.findinsert(car1);
        if (findinsert>0){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }
    }

    @Test
    public void cidAll(){
//        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext("spring.xml");
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        CarService car = context.getBean(CarService.class);
        Car selectcid = car.selectcid(1);
        System.out.println(selectcid);
    }

    @Test
    public void upd(){
//        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext("spring.xml");
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        CarService car = context.getBean(CarService.class);
        Car car1=new Car();
        car1.setCid(1);
        car1.setCnumber("豫W8888");
        car1.setType("拖拉机");
        int update = car.update(car1);
        System.out.println(update);
    }

    @Test
    public void del(){
//        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext("spring.xml");
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        CarService car = context.getBean(CarService.class);
        int del = car.del(5);
        if (del>0){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
    }
}

 测试全查

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值