MyBatis入门案列

MyBatis入门案列


开发Mybatis程序的步骤:

1、配置mybatis
conf.xml: 配置数据库信息 和 需要加载的映射文件

2、表 - 类
映射文件xxMapper.xml: 增删改查标签



DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.lanqiao.entity.personMapper">

	<select id="queryPersonById" resultType="org.lanqiao.entity.Person" parameterType="int">
		select * from person where id = #{id}
	select>

mapper>

4、编写测试类TestMybatis.java

session.selectOne(“需要查询的SQL的namespace.id”, “SQL的参数值”);


package org.lanqiao.entity;

import java.io.IOException;
import java.io.Reader;

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 TestMybatis {
	public static void main(String[] args) throws IOException {
		// 加载myBatis配置文件(为了访问数据库)
		Reader reader = Resources.getResourceAsReader("conf.xml");
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// SqlSessionFactory connection
		SqlSession session = sessionFactory.openSession();
		String statement = "org.lanqiao.entity.personMapper.queryPersonById";
		Person person = session.selectOne(statement,1);
		System.out.println(person);
		session.close();

	}

}


5、执行结果

MyBatis入门案列_第1张图片


6、小结

  1. parameterType=“int”> 的 int 对应 select 语句的 #{id}
select * from person where id = #{id}
  1. namespace:映射文件的路径

你可能感兴趣的:(MyBatis,java,Oracle,mybatis,java,oracle)