MyBatis+MySQL的,记录如下:
①数据库
在MySQL中,test数据库下,简历user表,一共两个字段id和name,建表语句略。
②需导入的包
只有两个:
mybatis-3.0.3.jar
mysql-connector-java-5.1.9-bin.jar(JDBC包)
③目录结构
采用最简单的结构,domain包下有且仅有四个文件
configuration.xml
User.xml
User.java
Test.java
④实体类javabean,总共两个变量
view plaincopy to clipboardprint?
1 package domain;
2
3 publicclass User {
4 privateint id;
5 private String name = null;
6 public User() {
7 }
8 public User(int id, String name) {
9 this.id = id;
10 this.name = name;
11 }
12 publicint getId() {
13 return id;
14 }
15 publicvoid setId(int id) {
16 this.id = id;
17 }
18 public String getName() {
19 return name;
20 }
21 publicvoid setName(String name) {
22 this.name = name;
23 }
24 @Override
25 public String toString() {
26 return"User [id=" + id + ", name=" + name +"]";
27 }
28 }
⑤MyBatis总配置文件configuration.xml
view plaincopy to clipboardprint?
29 <?xml version="1.0" encoding="UTF-8" ?>
30 <!DOCTYPE configuration PUBLIC
31 "-//mybatis.org//DTD Config 3.0//EN"
32 "http://mybatis.org/dtd/mybatis-3-config.dtd">
33 <configuration>
34 <typeAliases>
35 <typeAlias alias="User" type="domain.User" />
36 </typeAliases>
37 <environmentsdefault="development">
38 <environment id="development">
39 <transactionManager type="JDBC" />
40 <dataSource type="POOLED">
41 <property name="driver" value="com.mysql.jdbc.Driver" />
42 <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
43 <property name="username" value="root" />
44 <property name="password" value="" />
45 </dataSource>
46 </environment>
47 </environments>
48 <mappers>
49 <mapper resource="domain/User.xml" />
50 </mappers>
51 </configuration>
⑥User类的配置文件User.xml
view plaincopy to clipboardprint?
52 <?xml version="1.0" encoding="UTF-8" ?>
53 <!DOCTYPE mapper PUBLIC
54 "-//mybatis.org//DTD Mapper 3.0//EN"
55 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
56 <mapper namespace="User">
57 <select id="selectUser" parameterType="int" resultType="User"><!--[CDATA[
58 select * from user where id = #{id}
59 ]]--></select>
60 </mapper>
⑦测试用例
61 package domain;
62
63 import java.io.IOException;
64 import java.io.Reader;
65 import org.apache.ibatis.io.Resources;
66 import org.apache.ibatis.session.SqlSession;
67 import org.apache.ibatis.session.SqlSessionFactory;
68 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
69 import domain.User;
70
71 publicclass Test {
72 publicstaticvoid main(String[] args) throws IOException {
73 String resource ="domain/configuration.xml";
74 Reader reader = Resources.getResourceAsReader(resource);
75 SqlSessionFactory ssf =new SqlSessionFactoryBuilder().build(reader);
76 SqlSession session = ssf.openSession();
77 try {
78 User user = (User) session.selectOne("selectUser","1");
79 System.out.println(user);
80 }catch (Exception e) {
81 e.printStackTrace();
82 }finally {
83 session.close();
84 }
85 }
86 }