mybatis之注解式开发

Posted wq9

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis之注解式开发相关的知识,希望对你有一定的参考价值。

注解

  • 注解是用于描述代码的代码。例如:@Test(用于描述方法进行junit测试),@Override(用于描述方法的重写),@Param(用于描述属性的名称)
  • 注解的使用风格:@xxx(属性),使用前必须进行导包
  • 使用注解一般用于简化配置文件,但是注解有时候也不是很友好(有时候反而更麻烦),例如动态sql
  • 关于注解的属性

属性的设定方式是:属性名=属性值

  • 关于属性的类型
  1. 基本类型和String,可以直接使用双引号的形式
  2. 数组类型,name={值1,值2,......}如果数组元素只有一个,可以省略大括号。
  3. 对象类型,[email protected]对象名(属性)
  4. 如果属性是该注解的默认注解,而且该注解只配置这一个属性,key将属性名省略。

mybatis注解之CURD代码如下

 1 package com.bjsxt.mapper;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.annotations.Delete;
 6 import org.apache.ibatis.annotations.Insert;
 7 import org.apache.ibatis.annotations.Select;
 8 import org.apache.ibatis.annotations.Update;
 9 
10 import com.bjsxt.pojo.Student;
11 
12 public interface StudentMapper {
13 
14     @Select("select * from t_student")
15     List<Student> selAll();
16     
17     @Insert("insert into t_student values (default, #{name}, #{age}, #{gender}, #{cid})")
18     int insStu(Student student);
19     
20     @Update("update t_student set age=#{1} where id=#{0}")
21     int updStu(int id, int age);
22     
23     @Delete("delete from t_student where id=#{0}")
24     int delStu(int id);
25 }

 

 

  1 package com.bjsxt.pojo;
  2 
  3 import java.io.Serializable;
  4 
  5 public class Student implements Serializable {
  6 
  7     private int id;
  8     private String name;
  9     private int age;
 10     private String gender;
 11     private int cid;
 12 
 13     public Student() {
 14         super();
 15     }
 16 
 17     public int getId() {
 18         return id;
 19     }
 20 
 21     public void setId(int id) {
 22         this.id = id;
 23     }
 24 
 25     public String getName() {
 26         return name;
 27     }
 28 
 29     public void setName(String name) {
 30         this.name = name;
 31     }
 32 
 33     public int getAge() {
 34         return age;
 35     }
 36 
 37     public void setAge(int age) {
 38         this.age = age;
 39     }
 40 
 41     public String getGender() {
 42         return gender;
 43     }
 44 
 45     public void setGender(String gender) {
 46         this.gender = gender;
 47     }
 48 
 49     public int getCid() {
 50         return cid;
 51     }
 52 
 53     public void setCid(int cid) {
 54         this.cid = cid;
 55     }
 56 
 57     @Override
 58     public int hashCode() {
 59         final int prime = 31;
 60         int result = 1;
 61         result = prime * result + age;
 62         result = prime * result + cid;
 63         result = prime * result + ((gender == null) ? 0 : gender.hashCode());
 64         result = prime * result + id;
 65         result = prime * result + ((name == null) ? 0 : name.hashCode());
 66         return result;
 67     }
 68 
 69     @Override
 70     public boolean equals(Object obj) {
 71         if (this == obj)
 72             return true;
 73         if (obj == null)
 74             return false;
 75         if (getClass() != obj.getClass())
 76             return false;
 77         Student other = (Student) obj;
 78         if (age != other.age)
 79             return false;
 80         if (cid != other.cid)
 81             return false;
 82         if (gender == null) {
 83             if (other.gender != null)
 84                 return false;
 85         } else if (!gender.equals(other.gender))
 86             return false;
 87         if (id != other.id)
 88             return false;
 89         if (name == null) {
 90             if (other.name != null)
 91                 return false;
 92         } else if (!name.equals(other.name))
 93             return false;
 94         return true;
 95     }
 96 
 97     @Override
 98     public String toString() {
 99         return "Student [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", cid=" + cid + "]";
100     }
101 }

 

 1 package com.bjsxt.test;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.session.SqlSession;
 6 import org.junit.Test;
 7 
 8 import com.bjsxt.mapper.StudentMapper;
 9 import com.bjsxt.pojo.Student;
10 import com.bjsxt.util.MyBatisUtil;
11 
12 public class TestStu {
13 
14     @Test
15     public void testSel() {
16         SqlSession session = MyBatisUtil.getSession();
17         
18         StudentMapper mapper = session.getMapper(StudentMapper.class);
19         
20         List<Student> list = mapper.selAll();
21         for (Student student : list) {
22             System.out.println(student);
23         }
24         
25         session.close();
26     }
27     @Test
28     public void testIns() {
29         SqlSession session = MyBatisUtil.getSession();
30         
31         StudentMapper mapper = session.getMapper(StudentMapper.class);
32         
33         Student student = new Student();
34         student.setName("小王");
35         student.setAge(20);
36         student.setGender("女");
37         student.setCid(2);
38         
39         int num = mapper.insStu(student);
40         if(num > 0) {
41             System.out.println("ok");
42             session.commit();
43         } else {
44             session.rollback();
45         }
46         
47         session.close();
48     }
49     @Test
50     public void testUpd() {
51         SqlSession session = MyBatisUtil.getSession();
52         
53         StudentMapper mapper = session.getMapper(StudentMapper.class);
54         
55         int num = mapper.updStu(6, 30);
56         if(num > 0) {
57             System.out.println("ok");
58             session.commit();
59         } else {
60             session.rollback();
61         }
62         
63         session.close();
64     }
65     @Test
66     public void testDel() {
67         SqlSession session = MyBatisUtil.getSession();
68         
69         StudentMapper mapper = session.getMapper(StudentMapper.class);
70         
71         int num = mapper.delStu(6);
72         if(num > 0) {
73             System.out.println("ok");
74             session.commit();
75         } else {
76             session.rollback();
77         }
78         
79         session.close();
80     }
81 }

 

 

 1 package com.bjsxt.util;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 
11 public class MyBatisUtil {
12 
13     private static SqlSessionFactory factory = null;
14 
15     static {
16         try {
17             InputStream is = Resources.getResourceAsStream("mybatis-cfg.xml");
18             factory = new SqlSessionFactoryBuilder().build(is);
19         } catch (IOException e) {
20             e.printStackTrace();
21         }
22     }
23 
24     public static SqlSession getSession() {
25         SqlSession session = null;
26         if (factory != null) {
27             // true表示开启自动提交
28             // session = factory.openSession(true);
29             session = factory.openSession();
30         }
31         return session;
32     }
33 }

 

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/java505
3 jdbc.username=root
4 jdbc.password=root

 

 

 1 # Set root category priority to INFO and its only appender to CONSOLE.
 2 log4j.rootCategory=ERROR, CONSOLE
 3 # log4j.rootCategory=DEBUG, CONSOLE, LOGFILE
 4 
 5 # 单独设置SQL语句的输出级别为DEBUG级别
 6 log4j.logger.com.bjsxt.mapper=DEBUG
 7 
 8 # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
 9 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
10 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
11 log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n
12 
13 # LOGFILE is set to be a File appender using a PatternLayout.
14 log4j.appender.LOGFILE=org.apache.log4j.FileAppender
15 log4j.appender.LOGFILE.File=d:/test.log
16 log4j.appender.LOGFILE.Append=true
17 log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
18 log4j.appender.LOGFILE.layout.ConversionPattern=- %m %l%n

 

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <!-- properties加载外部文件 -->
 7     <properties resource="db.properties" />
 8     <!-- settings标签 -->
 9     <settings>
10         <!-- 设置MyBatis使用log4j日志支持 -->
11         <setting name="logImpl" value="LOG4J"/>
12     </settings>
13     <!-- typeAliases给类型起别名 -->
14     <typeAliases>
15         <package name="com.bjsxt.pojo" />
16     </typeAliases>
17     <environments default="dev">
18         <environment id="dev">
19             <transactionManager type="JDBC" />
20             <dataSource type="POOLED">
21                 <property name="driver" value="${jdbc.driver}"/>
22                 <property name="url" value="${jdbc.url}"/>
23                 <property name="username" value="${jdbc.username}"/>
24                 <property name="password" value="${jdbc.password}"/>
25             </dataSource>
26         </environment>
27     </environments>
28     <mappers>
29         <package name="com.bjsxt.mapper" />
30     </mappers>
31 </configuration>

 

以上是关于mybatis之注解式开发的主要内容,如果未能解决你的问题,请参考以下文章

JAVAEE框架技术之10-myBatis注解式开发

MyBatis| MyBatis的注解式开发

13.MyBatis注解式开发

Mybatis 教程之Mybatis注解开发

MyBatis注解开发之一对多查询

MyBatis注解开发之多对多查询