• Mybatis学习——基本增删改查(CRUD)


    Eclipse+Mybatis+MySql

      1.所需jar

      2.项目目录

      3.源代码

     1 package com.zhengbin.entity;
     2 
     3 public class Student {
     4     private int id;
     5     private String name;
     6     private double score;
     7     @Override
     8     public String toString() {
     9         return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
    10     }
    11     public int getId() {
    12         return id;
    13     }
    14     public void setId(int id) {
    15         this.id = id;
    16     }
    17     public String getName() {
    18         return name;
    19     }
    20     public void setName(String name) {
    21         this.name = name;
    22     }
    23     public double getScore() {
    24         return score;
    25     }
    26     public void setScore(double score) {
    27         this.score = score;
    28     }
    29     public Student(int id, String name, double score) {
    30         super();
    31         this.id = id;
    32         this.name = name;
    33         this.score = score;
    34     }
    35     // *注意这个必须加
    36     public Student() {
    37         super();
    38     }
    39 }
    Student.java
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     3 <!-- 每个映射文件的namespace应该是唯一的 -->
     4 <mapper namespace="com.zhengbin.entity.studentMapper">
     5     <!-- parameterType 参数表示需要参数的类型 -->
     6     <!-- resultType 参数表示返回结果的类型,该可以写为实体包的全路径,或者在conf.xml配置文件中,声明实体的别名 -->
     7     <select id="getStudent" parameterType="int" resultType="Student">
     8         select * from student where id=#{id}
     9     </select>
    10     
    11     <select id="getAllStudent" resultType="Student">
    12         select * from student
    13     </select>
    14     
    15     <insert id="addStudent" parameterType="Student">
    16         insert into student(name,score) values(#{name},#{score})
    17     </insert>
    18     
    19     <update id="updateStudent" parameterType="Student">
    20         update student set name=#{name},score=#{score} where id=#{id}
    21     </update>
    22     
    23     <delete id="deleteStudent" parameterType="int">
    24         delete from student where id=#{id}
    25     </delete>
    26 </mapper>
    studentMapper.xml
     1 package com.zhengbin.entity2;
     2 
     3 
     4 import org.apache.ibatis.annotations.Select;
     5 
     6 import com.zhengbin.entity.Student;
     7 
     8 public interface studentMapper {
     9     @Select("select * from student where id=#{id}")
    10     public Student testGet(int id);
    11 }
    studentMapper.java
     1 package com.zhengbin.test;
     2 
     3 import java.util.List;
     4 
     5 import org.apache.ibatis.session.SqlSession;
     6 import org.apache.ibatis.session.SqlSessionFactory;
     7 
     8 import com.zhengbin.entity.Student;
     9 import com.zhengbin.util.MyBatisUtils;
    10 
    11 public class Test {
    12     @org.junit.Test
    13     public void testGet(){
    14         SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
    15         // 参数为TRUE,相当于session.commit();
    16         SqlSession session = sessionFactory.openSession(true);
    17         // 读取映射文件
    18         String statement = "com.zhengbin.entity.studentMapper" + ".getStudent";
    19         Student s = session.selectOne(statement,5);
    20         System.out.println(s);
    21         session.close();
    22     }
    23     
    24     @org.junit.Test
    25     public void testGetAll(){
    26         SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
    27         // 参数为TRUE,相当于session.commit();
    28         SqlSession session = sessionFactory.openSession(true);
    29         // 读取映射文件
    30         String statement = "com.zhengbin.entity.studentMapper" + ".getAllStudent";
    31         List<Student> list = session.selectList(statement);
    32         System.out.println(list);
    33         session.close();
    34     }
    35     
    36     @org.junit.Test
    37     public void testAdd(){
    38         SqlSessionFactory sessionFactory =  MyBatisUtils.getFactory();
    39         SqlSession session = sessionFactory.openSession(true);
    40         String statement = "com.zhengbin.entity.studentMapper" + ".addStudent";
    41         Student s = new Student();
    42         s.setName("zhengB");
    43         s.setScore(95.9);
    44         int insert = session.insert(statement, s);
    45         System.out.println(insert);
    46         session.close();
    47     }
    48     
    49     @org.junit.Test
    50     public void testUpdate(){
    51         SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
    52         SqlSession session = sessionFactory.openSession(true);
    53         String statement = "com.zhengbin.entity.studentMapper" + ".updateStudent";
    54         Student s = new Student();
    55         s.setId(14);
    56         s.setName("zhengbin");
    57         s.setScore(96);
    58         int update = session.update(statement, s);
    59         System.out.println(update);
    60         session.close();
    61     }
    62     
    63     @org.junit.Test
    64     public void testDelete(){
    65         SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
    66         SqlSession session = sessionFactory.openSession(true);
    67         String statement = "com.zhengbin.entity.studentMapper" + ".deleteStudent";
    68         int delete = session.delete(statement,21);
    69         System.out.println(delete);
    70         session.close();
    71     }
    72 }
    Test.java
     1 package com.zhengbin.test;
     2 
     3 import org.apache.ibatis.session.SqlSession;
     4 import org.apache.ibatis.session.SqlSessionFactory;
     5 
     6 import com.zhengbin.entity.Student;
     7 import com.zhengbin.entity2.studentMapper;
     8 import com.zhengbin.util.MyBatisUtils;
     9 
    10 public class Test2 {
    11     @org.junit.Test
    12     public void testGet(){
    13         SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();
    14         SqlSession session = sessionFactory.openSession(true);
    15         studentMapper mapper = session.getMapper(studentMapper.class);
    16         Student s = mapper.testGet(14);
    17         System.out.println(s);
    18         session.close();
    19     }
    20 }
    Test2.java
     1 package com.zhengbin.util;
     2 
     3 import java.io.InputStream;
     4 
     5 import org.apache.ibatis.session.SqlSessionFactory;
     6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     7 
     8 public class MyBatisUtils {
     9     public static SqlSessionFactory getFactory(){
    10         String resource = "conf.xml";
    11         InputStream is = MyBatisUtils.class.getClassLoader().getResourceAsStream(resource);
    12         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
    13         return sessionFactory;
    14     }
    15 }
    MyBatisUtils.java
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
     3 <configuration>
     4     <!-- 数据库配置文件 -->     
     5      <properties resource="jdbc.properties"/>
     6      <!-- 取别名 -->
     7      <typeAliases>
     8          <!-- 方式一、为类取别名 -->
     9          <!-- <typeAlias type="com.zhengbin.entity.Student" alias="_Student"/> -->
    10          <!-- 方式二、自动以类名为别名 -->
    11          <package name="com.zhengbin.entity"/>
    12      </typeAliases>
    13     <!-- 
    14         development : 开发模式
    15         work : 工作模式
    16      -->
    17     <environments default="development">
    18         <environment id="development">
    19             <transactionManager type="JDBC" />
    20             <dataSource type="POOLED">
    21                 <property name="driver" value="${driver}" />
    22                 <property name="url" value="${url}" />
    23                 <property name="username" value="${username}" />
    24                 <property name="password" value="${password}" />
    25             </dataSource>
    26         </environment>
    27     </environments>
    28     <mappers>
    29         <!-- 这是一个路径的结构,不是包的结构 -->
    30         <mapper resource="com/zhengbin/entity/studentMapper.xml"/>
    31         <mapper class="com.zhengbin.entity2.studentMapper"/>
    32     </mappers>
    33 </configuration>
    conf.xml
    1 driver=com.mysql.jdbc.Driver
    2 url=jdbc:mysql://localhost:3307/student
    3 username=root
    4 password=950906
    jdbc.properties
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
     3 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
     4     <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
     5         <layout class="org.apache.log4j.PatternLayout">
     6             <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) 
    " />
     7         </layout>
     8     </appender>
     9     <logger name="java.sql">
    10         <level value="debug" />
    11     </logger>
    12     <logger name="org.apache.ibatis">
    13         <level value="debug" />
    14     </logger>
    15     <root>
    16         <level value="debug" />
    17         <appender-ref ref="STDOUT" />
    18     </root>
    19 </log4j:configuration>
    log4j.xml

      4.遇到的问题

    (1)奇怪的junit:如果新建一个class,名为Test则可能出现不能使用注解@Test的情况,此时用@org.junit.Test即可,或者更改class名,不以Test开头 好奇葩

    (2)实体类必须要加superclass,否则报错,因为MyBatis无法通过配置文件找到实体类

  • 相关阅读:
    N层电梯只停一层情况下,求所有人爬楼层数最少
    小组开发用户调研
    《哈利波特》买书最优惠算法
    团队开发——极速蜗牛
    林锐——软件工程思想后两章阅读笔记
    课堂练习之检测水军
    团队开发项目-----来用------典型用户与用户场景分析
    体验结对开发的乐趣(6)--(电梯调度问题)
    团队开发项目-----来用------用户需求调研报告
    课堂练习之最高折扣,最低优惠规划
  • 原文地址:https://www.cnblogs.com/zhengbin/p/5266264.html
Copyright © 2020-2023  润新知