mybatis的快速入门

说明:

  在这个部分,会写个简单的入门案例。

  然后,会重新写一个,更加严格的程序案例。

一:案例一

1.最终的目录结构

  mybatis的快速入门

2.新建一个普通的Java项目,并新建lib

  在项目名上右键,不是src。

  mybatis的快速入门

3.导入需要的jar包,并加入到classpath中

  mybatis-3.4.5.jar
  mysql-connector-java-5.1.18-bin.jar

  mybatis的快速入门

4.新建数据库与表

 CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE users(
ID INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
AGE INT
);
INSERT INTO users(NAME,age) VALUES("TOM",12);
INSERT INTO users(NAME,AGE) VALUES("JACK",11);

mybatis的快速入门

5.新建bean--User.java

 package com.test;

 public class User {
private int id;
private String name;
private int age;
public User() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
} }

6.新建配置文件--Configuration.xml 

resource="users.xml",注意的是,这个不需要加/。
 <?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3308/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="users.xml"/>
</mappers> </configuration>

7.新建映射文件--users.xml

  在这个映射文件中,需要注意的是,需要写result Map,不然找不到返回值。

 <?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="quickFirst">
<resultMap type="com.test.User" id="User">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="NAME" jdbcType="VARCHAR" property="name"/>
<result column="AGE" jdbcType="INTEGER" property="age"/>
</resultMap> <select id="selectUser" parameterType="int" resultMap="User">
SELECT * From users where id = #{id};
</select>
</mapper>

8.测试类--TestSelectById.java

  这个类中使用的是反射的形式来获取配置文件。

  需要注意的是:String resources="/Configuration.xml",这个需要增加/。

 package com.test;

 import java.io.InputStream;

 import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class TestSelectById {
public static void main(String[] regs) {
String resources="/Configuration.xml";
InputStream is=TestSelectById.class.getResourceAsStream(resources);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession=sqlSessionFactory.openSession();
String statement="quickFirst.selectUser";
User user=sqlSession.selectOne(statement, 1);
System.out.println(user);
}
}

9.效果图

  mybatis的快速入门

二:案例二

1.程序最终目录

  mybatis的快速入门

2.新建表

 DROP TABLE IF EXISTS `message`;
CREATE TABLE `message` (
`ID` int(20) AUTO_INCREMENT COMMENT '主键',
`COMMAND` varchar(16) DEFAULT NULL COMMENT '指令名称',
`DESCRIPTION` varchar(32) DEFAULT NULL COMMENT '描述',
`CONTENT` varchar(2048) DEFAULT NULL COMMENT '内容',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; INSERT INTO `message` VALUES ('', '查看', '精彩内容', '精彩内容');
INSERT INTO `message` VALUES ('', '段子', '精彩段子', '如果你的月薪是3000块钱');
INSERT INTO `message` VALUES ('', '新闻', '今日头条', '7月17日,马来西亚一架载有298人');
INSERT INTO `message` VALUES ('', '娱乐', '娱乐新闻', '昨日,邓超在微博分享了自己和孙俪的书法。');
INSERT INTO `message` VALUES ('', '电影', '近日上映大片', '《忍者神龟》');

  mybatis的快速入门

3.新建Message.java

 package com.cao.bean;
/**
* message��
* @author dell
*
*/
public class Message {
private int id;
private String command;
private String description;
private String content;
public Message() {}
public Message(int id, String command, String description, String content) {
super();
this.id = id;
this.command = command;
this.description = description;
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
} }

4.新建配置文件

 <?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3308/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/cao/config/Message.xml"/>
</mappers> </configuration>

5.新建映射文件

 <?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="Message"> <resultMap type="com.cao.bean.Message" id="MessageResult">
<id column="ID" jdbcType="INTEGER" property="id"/>
<result column="COMMAND" jdbcType="VARCHAR" property="command"/>
<result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
<result column="CONTENT" jdbcType="VARCHAR" property="content"/>
</resultMap> <select id="queryMessageList" parameterType="com.cao.bean.Message" resultMap="MessageResult">
SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM message WHERE 1=1
</select> </mapper>

6.新建DBAccess.java,链接数据库

 package com.cao.db;

 import java.io.IOException;
import java.io.Reader; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class DBAccess {
public SqlSession getSqlSession() throws Exception {
//获取数据库的连接信息
Reader reader=Resources.getResourceAsReader("com/cao/config/Configuration.xml"); //
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); //
SqlSession sqlSession=sqlSessionFactory.openSession(); System.out.println(sqlSession);
return sqlSession;
}
}

7.新建Dao,操作数据库

 package com.cao.dao;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.session.SqlSession; import com.cao.bean.Message;
import com.cao.db.DBAccess; /**
* 和message相关的dao
* @author dell
*
*/
public class MessageDao {
/**
* 查询以及包括条件查询
* @param command
* @param description
* @return
*/
public List<Message> queryMessageList() {
List<Message> messageList=new ArrayList<>();
SqlSession sqlSession=null;
/**
* MyBatis
*/
DBAccess dbAccess=new DBAccess();
try {
//封装,方便将参数传进到xml中
Message message=new Message();
sqlSession=dbAccess.getSqlSession();
messageList=sqlSession.selectList("Message.queryMessageList",message); } catch (Exception e) { e.printStackTrace();
}finally {
sqlSession.close();
} return messageList; }
}

8.新建service,数据处理层

 package com.cao.service;

 import java.util.List;

 import com.cao.bean.Message;
import com.cao.dao.MessageDao; /**
* 列表相关的业务功能
* @author dell
*
*/
public class ListService {
public List<Message> queryMessageList() {
MessageDao messageDao=new MessageDao();
return messageDao.queryMessageList();
}
}

9.测试类

 package com.cao.main;

 import java.util.Iterator;
import java.util.List; import com.cao.bean.Message;
import com.cao.service.ListService; public class TestSelectList {
public static void main(String[] args) {
ListService listService=new ListService();
List messageList=listService.queryMessageList();
Iterator it=messageList.iterator();
while(it.hasNext()) {
Message message=(Message)it.next();
String com=message.getCommand();
System.out.println(com);
}
}
}

10,结果

  mybatis的快速入门

  

上一篇:解决 requests.exceptions.SSLError: HTTPSConnectionPool 异常


下一篇:Java反射机制探秘