1. 程式人生 > >使用MyBatis(一)使用xml配置完成查詢單行資料

使用MyBatis(一)使用xml配置完成查詢單行資料

使用MyBatis前要先安裝資料庫,我用mysql 

1.config.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ywdb
username=root
password=root

2.實體類

package com.yw.test01;

public class User
{
	private int id;
	private String name;
	private int age;
	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 + "]";
	}
	
	
	
}

3.UserMapper.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.yw.test01.UserMapper">
  <select id="selectUser" resultType="com.yw.test01.User">
    select * from user where id = #{id}
  </select>
</mapper>

4.mybatis-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>
	<properties resource="config.properties">

	</properties>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<!-- <mapper resource="org/mybatis/example/BlogMapper.xml"/> -->
		<mapper resource="com/yw/test01/UserMapper.xml" />
	</mappers>
</configuration>

5.測試類

Test01.java

package com.yw.test01;

import java.io.IOException;
import java.io.InputStream;



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 Test01
{
	public static void main(String[] args) throws IOException
	{
		
		String resource = "com/yw/test01/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		SqlSession session = sqlSessionFactory.openSession();
		try {
		  User user = (User) session.selectOne("com.yw.test01.UserMapper.selectUser", 1);
		  System.out.println(user);
		  
		} finally {
		  session.close();
		}
	}
}

6.效果