Mybatis查询示例
官网上面对mybatis入门示例介绍的很清楚了
https://mybatis.org/mybatis-3/zh/index.html
下面在idea中使用mybatis做个示例
整个流程图如下:
首先需要有个数据库表,在这里使用本地的learn库demo表
首先mybatis主配置文件
<?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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/learn"/>
<property name="username" value="root"/>
<property name="password" value="jiahongtai"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="Demo.xml"/>
</mappers>
</configuration>
想要得到的pojo类
public class Demo {
int id;
String name;
@Override
public String toString() {
return "Demo{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
查询接口
public interface DemoDao {
Demo selectById(int id);
String selectByIdGetName(int id);
}
mapper配置文件
<?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="learnMybatis.DemoDao">
<select id="selectById" resultType="learnMybatis.Demo">
select * from demo where id = #{id}
</select>
<select id="selectByIdGetName">
select * from demo where id=#{id}
</select>
</mapper>
注意:在maven下,不要将xml文件放到源目录下,在java目录下只会解析java文件,可以将xml放到resources目录下
测试main类
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 java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) throws IOException {
String resource = "settings.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
DemoDao mapper = session.getMapper(DemoDao.class);
Demo demo = mapper.selectById(1);
System.out.println(demo);
}
}
执行结果: