Mybatis > 学习 1
From: http://qiuqiu0034.iyunv.com/blog/1157768#bc2302703mybatis-3.0.3.jar http://code.google.com/p/mybatis/
mysql-connector-java-5.1.9-bin.jar(JDBC包)
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>
<environments default="myexample">
<environment id="myexample">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test_1" />
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<!-- 要执行的sql语句 -->
<mappers>
<mapper resource="com/mft/cfg/mapper_person.xml"/>
</mappers>
</configuration>
mapper_person.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.mft.cfg">
<select id="selectUserById" parameterType="int" resultType="com.mft.conn.Person">
select * from person where id=#{id}
</select>
</mapper>
Person.java
package com.mft.conn;
public class Person {
private int id;
private String name;
private int age;
private String sex;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
homeIndex.java
package home.mft;
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.mft.conn.Person;
public class homeIndex {
public static void main(String[] args) {
SqlSessionFactory factory = null;
try {
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("com/mft/cfg/config.xml"));
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
SqlSession sqlSession = factory.openSession();
Person p = (Person)sqlSession.selectOne("selectUserById",2);
System.out.println(p.getName());
}
}
页:
[1]