欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis使用篇之二:HelloWorld

程序员文章站 2022-06-19 17:47:56
...

1. 搭建开发环境

(1)新建一个Web工程,名称为MybatisFramework。

 

(2)将以下的JAR放到Web工程的lib下面:

mybatis-3.0.6.jar
og4j-1.2.16.jar
classes12.jar

 

(3)在src下面新建log4j.properties文件,该文件的内容如下:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] -%m%n
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug,stdout

 

(4)在src下面新建mybatis.cfg.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" />
            <dataSource type="POOLED">
              <property name="driver" value="oracle.jdbc.OracleDriver" />
              <property name="url" value="jdbc:oracle:thin:@localhost:1521:SID" />
              <property name="username" value="xxxx" />
              <property name="password" value="xxxx" />
            </dataSource>
        </environment>
    </environments>
   
    </configuration>

 

 

2. 入门示例

(1)在Oracle数据库执行以下SQL,创建一个USER_INFO的表:

-- Create table
create table USER_INFO
(
  ID          NUMBER(12) not null,
  NAME        VARCHAR2(50)
);

--Insert data
insert into USER_INFO(ID,NAME) values(1,'张三');

 

(2)新建一个Java类UserInfo.java,该类的内容如下:

 

package com.user;

public class UserInfo {
	private int id;
	private String name;

	public UserInfo() {
	}

	public UserInfo(String name) {
		this(0, name);
	}

	public UserInfo(int id, String name) {
		this.id = id;
		this.name = name;
	}

	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;
	}

	@Override
	public String toString() {
		return "ID: " + id + ", Name: " + name;
	}
}

 

(3)在com.user.sqlmap下面新建UserInfo.xml文件,该文件的内容如下:

 

<?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="User">
    <select id="selectUser" parameterType="int" resultType="UserInfo">
    <![CDATA[
        select * from user_info where id = #{id}
    ]]>
    </select>
</mapper>

 

(4)将UserInfo.xml引用到mybatis.cfg.xml文件中,mybatis.cfg.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>
    <typeAliases>
        <typeAlias alias="UserInfo" type="com.user.UserInfo" />
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
              <property name="driver" value="oracle.jdbc.OracleDriver" />
              <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORACLEDB" />
              <property name="username" value="oracle" />
              <property name="password" value="oracle" />
            </dataSource>
        </environment>
    </environments>
   
    <mappers>
        <mapper resource="com/user/sqlmap/UserInfo.xml" />
    </mappers>
</configuration>

 

(5)新建一个测试Java类UserInfoTest.java,该类的具体内容如下:

package com.user;

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 UserInfoTest {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		String resource = "mybatis.cfg.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
        
        SqlSession session = ssf.openSession();
        
        try {
        	UserInfo user = (UserInfo) session.selectOne("User.selectUser", "1");
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
	}

}

 

(6)右键UserInfoTest 类,选择Run As Application,运行MyBaits操作数据库。

 

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2012-02-11 21:44:01,750 DEBUG [java.sql.PreparedStatement] -==>  Executing: select * from user_info where id = ? 
2012-02-11 21:44:01,781 DEBUG [java.sql.PreparedStatement] -==> Parameters: 1(String)
ID: 1, Name: 张三