<?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:指默认使用id为defaultr的 environment配置 一个environments下可以有多个environment--> <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="admin"/> </dataSource> </environment> </environments> <!-- 读取mapper --> <mappers> <mapper resource="com/strong/mapper/FlowerMapper.xml"/> </mappers> </configuration>
<?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"> <!-- namespace:命名,可以随意取 --> <mapper namespace="com.strong.mapper"> <!-- resultType:实体类,要写类命名 id:命名 --> <select resultType="com.strong.pojo.Flower" id="selectAll"> select * from flower </select> </mapper>
public class Test { public static void main(String[] args) throws IOException { //读取XML文件 InputStream is=Resources.getResourceAsStream("myBatis.xml"); //创建SqlSessionFactory工厂 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is); //生产一个SqlSession对象 SqlSession session=factory.openSession(); //读取数据库 List<Flower> list=session.selectList("com.strong.mapper.selectAll"); for(Flower flower:list) { System.out.println(flower); } } }
返回一个List对象,适用于查询需要遍历的结果
List<Flower> list=session.selectList("com.strong.mapper.selectAll"); for(Flower flower:list) { System.out.println(flower); }
<select resultType="com.strong.pojo.Flower" id="selectAll"> select * from flower </select>
返回一个Object对象,适用于查询一条数据
int count=session.selectOne("com.strong.mapper.selectOne"); System.out.println(count);
<select resultType="int" id="selectOne"> select count(*) from flower </select>
返回一个map,适用于需要对查询结果再次筛选(通讯录)
Map<Object,Object> map=session.selectMap("com.strong.mapper.selectMap", "name");//name为map的key
System.out.println(map);
<select resultType="com.strong.pojo.Flower" id="selectMap"> select * from flower </select>
原文:https://www.cnblogs.com/lastingjava/p/9926362.html