MybatisHelloWorld

u011167211發表於2015-01-20

//測試入口TestMyBatis
package com.base.helloworld.test;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.base.helloworld.bean.User;
import com.base.helloworld.mapper.Mapper;

/**
* @Description
* @author FuJianyong
* 2015-1-20下午04:25:27
*/
public class TestMyBatis {
public static SqlSessionFactory getSessionFactory() {
String config = "com/base/helloworld/config.xml";
SqlSessionFactory sessionFactory = null;
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(config));
} catch (IOException e) {
e.printStackTrace();
}
return sessionFactory;
}
public static void main(String[] args) {
SqlSession sqlSession = getSessionFactory().openSession();
Mapper mapper = sqlSession.getMapper(Mapper.class);
User user = mapper.selectById(2);
System.out.println(user.getName()+" "+user.getPassword());
}
}

//配置檔案config.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 type="com.base.helloworld.bean.User" alias="User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="jdbc" />
<dataSource type="POOLED" >
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.1.10:3306/xxx?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="xxx" />
<property name="password" value="xxx" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/base/helloworld/mapper/mapper.xml"/>
</mappers>
</configuration>
//模型User
package com.base.helloworld.bean;

public class User {

private String name;

private String password;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}

// 介面Mapper
package com.base.helloworld.mapper;

import com.base.helloworld.bean.User;

public interface Mapper {

User selectById(int id);

}

//運算元據庫mapper.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="com.base.helloworld.mapper.Mapper">
<select id="selectById" parameterType="int" resultType="User">
SELECT * FROM t_user where ID = #{id}
</select>
</mapper>