代码
Test.java
package com.bjsxt.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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.bjsxt.pojo.Flower;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("myabtis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
List<Flower> list = session.selectList("a.b.selAll");
for(Flower flower:list){
System.out.println(flower.toString());
}
session.close();
}
}
myabtis.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>
<!-- default引用environment的id,当前所使用的环境 -->
<environments default="default">
<!-- 声明可以使用的环境 -->
<environment id="default">
<!-- 使用原生JDBC事务 -->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/bjsxt/mapper/FlowerMapper.xml"/>
</mappers>
</configuration>
FlowerMapper.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 = "a.b">
<!-- id:方法名
parameterType:定义参数类型
resultType:返回值类型.
如果方法返回值是list,在resultType中写List的泛型,因为mybatis
对jdbc封装,一行一行读取数据
-->
<select id="selAll" resultType="com.bjsxt.pojo.Flower">
select * from flower
</select>
</mapper>
Flower.java
package com.bjsxt.pojo;
public class Flower {
private int id;
private String name;
private double price;
private String production;
public Flower(int id, String name, double price, String production) {
super();
this.id = id;
this.name = name;
this.price = price;
this.production = production;
}
public Flower() {
super();
}
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 double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getProduction() {
return production;
}
public void setProduction(String production) {
this.production = production;
}
@Override
public String toString() {
return "Flower [id=" + id + ", name=" + name + ", price=" + price + ", production=" + production + "]";
}
}
数据表,包