Mybaits增删改查的注解和xml开发(CRUD)

创建类:StudentMapper
相关的结构:
在这里插入图片描述

package com.mapper;

import com.zjj.pojo.Student;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentMapper {
    
    
     @Insert(value = "insert into student values(#{id},#{name},#{claz})")
     int addStudent(Student student);

     //不要mybatis.user要不然会报错
     @Select( value="select * from student")
    List<Student> getStudents();
    @Select(value ="select *from student where id=#{id}")
    List<Student> getStudentsById(int id);


    @Update("update student set id=#{id},name=#{name},claz=#{claz}")
    int updateStudent(Student student);

    @Delete("delete from student where id=#{id}")
    int deleteStudentById(int id);

    @Delete("delete from student where name=#{name}")
    int deleteStudentByName(String name);



}

创建Student类:

package com.zjj.pojo;

public class Student {
    
    
    Integer id;
    String name;
    String claz;


    public Integer getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getClaz() {
    
    
        return claz;
    }

    public void setClaz(String claz) {
    
    
        this.claz = claz;
    }

    public Student(Integer id, String name, String claz) {
    
    
        this.id = id;
        this.name = name;
        this.claz = claz;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", claz='" + claz + '\'' +
                '}';
    }

    public Student() {
    
    
    }
}

SqlConfigMap配置文件:

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

    <properties resource="jdbc.properties"></properties>


    <!--配置别名-->
    <typeAliases>
        <package name="com.mapper"/>
    </typeAliases>
    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>



    <!--绑定接口,之前绑定Mapper.xml文件的代码就不需要了只需要绑定一下接口就行了-->
    <mappers>
        <mapper class="com.mapper.StudentMapper"/>
    </mappers>



</configuration>
  

这里mapper里面的标签是class,不是resource,一定要注意
jdbc.properties文件(注意改自己的密码):

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=roothouzhicong

创建测试类:

import com.mapper.StudentMapper;
import com.zjj.pojo.Print;
import com.zjj.pojo.Student;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.InputStream;
import java.util.List;

public class Test {
    
    
   private InputStream in;
    private SqlSessionFactoryBuilder builder;
    private SqlSessionFactory factory;
    private  SqlSession sqlSession;
    private StudentMapper mapper;

    //Aop的测试方法
    @org.junit.Test
public void SpringAoptest(){
    
    
    ApplicationContext app=new ClassPathXmlApplicationContext("ApplicationContext.xml");
    Print print = app.getBean(Print.class);
    print.print();

}
@Before
    public void test() throws Exception{
    
    
    InputStream in= Resources.getResourceAsStream("SqlCofigMap.xml");
    SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
    SqlSessionFactory factory=builder.build(in);
    sqlSession=factory.openSession();
    //底层主要应用反射
    mapper = sqlSession.getMapper(StudentMapper.class);

    }
    @After
    public void Mybaitstest() throws Exception{
    
    

        //提交事务
        sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    @org.junit.Test
    //测试getStudents()方法
    public void getStudents(){
    
    


        List<Student> students = mapper.getStudents();

        for (Student student : students) {
    
    
            System.out.println(student);
        }


    }

    //        测试 getStudentsById()方法
    @org.junit.Test
    public void getStudentsById(){
    
    
        List<Student> students=mapper.getStudentsById(1);
        for (Student student : students) {
    
    
            System.out.println(student);
        }



    }



//    测试add方法
    @org.junit.Test

    public void addStudenttest(){
    
    
        Student student = new Student();
        student.setId(100);
        student.setName("dingxuejian");
        student.setClaz("软件一班");
        int i = mapper.addStudent(student);
        System.out.println(i);

    }


//    测试删除的方法
    @org.junit.Test

    public void deletetest(){
    
    
        int i = mapper.deleteStudentByName("侯治聪");
        System.out.println(i);

    }

    @org.junit.Test
    //测试更新的方法
    public void updatetest(){
    
    

        Student student=new Student();
        student.setId(2);
        student.setClaz("ruanjianerban");
        int i = mapper.updateStudent(student);
        System.out.println(i);

    }


}

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:p="http://www.springframework.org/schema/p"
       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-4.3.xsd
	 http://www.springframework.org/schema/context
	 http://www.springframework.org/schema/context/spring-context-4.3.xsd
	 http://www.springframework.org/schema/tx
	 http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
     http://www.springframework.org/schema/aop
	 http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!--基于xml方式来实现aop配置-->
    <bean id="p" class="com.zjj.pojo.Printer"></bean>
    <bean id="log" class="com.zjj.pojo.Logger"></bean>
    <bean id="time" class="com.zjj.pojo.Timer"></bean>

    <!--aop配置-->
    <aop:config>

        <!--配置切入点-->
        <aop:pointcut id="addMethods" expression="execution(* com.zjj.pojo.*.*(..) )"/>
        <!--配置切面1 order 优先级 值越小 优先级越高-->
        <aop:aspect id="t" ref="time" order="1">
            <aop:before method="showTime" pointcut-ref="addMethods"></aop:before>
            <aop:after method="showTime" pointcut-ref="addMethods"></aop:after>
        </aop:aspect>

        <!--配置切面2 order 优先级 值越小 优先级越高-->
        <aop:aspect id="l" ref="log" order="2">
            <aop:before method="loggerBefore" pointcut-ref="addMethods"></aop:before>
            <aop:after method="loggerAfter" pointcut-ref="addMethods"></aop:after>
        </aop:aspect>



    </aop:config>

</beans>   

对大家有帮助的话别忘记点赞,这个是我的动力,毕竟创作也不易,希望大家在编程中体会到无限的快乐。。。。。。

猜你喜欢

转载自blog.csdn.net/houzhicongone/article/details/115286250