下载网站:
https://github.com/mybatis/mybatis-3/releases
1.引入web项目下引入mybatis.jar
引入到WebRoot/WEB-INF/lib下
2.配置 mybatis 核心配置文件(这个在mybatis源码包中)
mybatis-3-mybatis-3.4.5\src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml
将Configuration.xml复制到web项目中
配置核心配置文件
<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://localhost:3306/micro_message"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/daoan/config/sqlxml/Message.xml"/> </mappers> </configuration>
3.得到sqlSession对象
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 IOException { //通过配置文件获取数据库连接信息 Reader reader = Resources.getResourceAsReader("com/daoan/config/Configuration.xml"); //通过配置信息构建SqlSessionFactoy SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); //通过SqlSessionFactoy打开一个数据库会话 SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession; } }
4.使用Mybatis框架来连接连接sql以及执行sql语句
/** * 和Message表相关的数据库操作 */ public class MessageDao { /** * 根据查询条件,查询消息列表 */ public List<Message> queryMessageList(String command,String description) { DBAccess dbAccess = new DBAccess(); List <Message> messageList = new ArrayList<Message>(); SqlSession sqlSession = null; try { sqlSession = dbAccess.getSqlSession(); //通过sqlSession执行SQL语句 messageList = sqlSession.selectList("Message.queryMessageList"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(sqlSession !=null){ sqlSession.close(); sqlSession = null; } } return messageList; } public static void main(String[] args) { MessageDao messageDao = new MessageDao(); messageDao.queryMessageList("", ""); } }
5.Message.xml配置文件 (取出数据库某个字段的值放在java的对象的属性里面)
<?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.daoan.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="Context" jdbcType="VARCHAR" property="context"/> </resultMap> <select id="queryMessageList" resultMap="MessageResult"> select Id,Command,Description,Context from message where 1=1 </select> </mapper>