在写一个很简单的入门级mybatis demo中,是直接通过xml来绑定mapper,这里使用接口来实现。
数据库仍使用之前的数据库
方法一:用约束来保证接口能够在XML中找到对应的SQL语句
在之前的demo项目下新建一个demo2.cyj包用于做接口的实现方式,最终项目结构如下:
最终目录结构
1. 将之前的mybatis_config.xml
和Student.java
拷到相应包下
2. 新建一个包dao,再新建接口StudentDao.java
,
package demo2.cyj.dao;
import demo2.cyj.pojo.Student;
public interface StudentDao{
public Student selectStuById(int id);
public int insertStu(String stu_name,int stu_age);
public int updateById(Map<String,Object> map);
}
3. 在mapper包下新建StudentMapper.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="demo2.cyj.dao.StudentDao">
<select id="selectStuById" parameterType="int" resultType="demo2.cyj.pojo.Student">
select * from student where id = #{id}
</select>
<insert id="insertStu">
insert into student(stu_name,stu_age) values(#{0},#{1})
</insert>
<update id="updateById" parameterType="map">
update student set stu_name = #{sname},stu_age=#{sage} where id=#{sid}
</update>
</mapper>
需要注意的是,mapper名空间和StudentDao接口的路径要一致,id和方法名一致,否则会报错:Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface demo2.cyj.dao.StudentDao is not known to the MapperRegistry.
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface demo2.cyj.dao.StudentDao is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:717)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:292)
at demo2.cyj.MybatisTest2.main(MybatisTest2.java:28)
4. 新建MybatisTest2.java
测试类进行测试
package demo2.cyj;
import java.io.IOException;
import java.io.InputStream;
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 demo2.cyj.dao.StudentDao;
import demo2.cyj.pojo.Student;
public class MybatisTest2 {
public static void main(String[] args) throws IOException {
// mybatis的配置文件的路径
String resource = "demo2/cyj/config/mybatis_config.xml";
// 读取配置文件的路径
InputStream inputStream = Resources.getResourceAsStream(resource);
// 获取到sqlSession的构造工厂类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 括号内加true,那么会自动提交,否则(括号内不传参)最后要手动提交
SqlSession session = sqlSessionFactory.openSession(true);
//通过session将StudentDao.java和StudentMapper.xml绑定起来,
//注意此方式中,mapper的名空间要和接口的路径一致,mapper的id要和接口的方法名一致
StudentDao studentDao = session.getMapper(StudentDao.class);
//在dao中指定了返回的类型是obj还是list,所以就不用特别指定selectOne还是selectList
//查找byId
Student s1 = studentDao.selectStuById(1);
System.out.println("select:"+s1);
//插入,通过逐个值传的方式
int i = studentDao.insertStu("拐", 50);
System.out.println("insert:"+i);
//修改,通过传递map的方式
Map<String,Object> map = new HashMap<>();
map.put("sname", "黑拐");
map.put("sage", 42);
map.put("sid", 8);
int b = studentDao.updateById(map);
System.out.println("update:"+b);
}
}
在这种方式中,与之前不同的是要通过StudentDao studentDao = session.getMapper(StudentDao.class)
,将mapper和接口绑定起来;
特别注意的一点是,这段代码中:
Student s1 = studentDao.selectStuById(1);
因为在dao中的接口方法声明上就指定了返回的类型是obj还是list,所以就不用特别指定selectOne还是selectList
附其他部分代码:
mybatis_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>
<!-- 配置默认开发环境,default中的值与下面的开发环境id对应 -->
<environments default="development">
<!-- 配置开发环境 -->
<environment id="development">
<!-- JDBC事务 -->
<transactionManager type="JDBC"/>
<!-- 连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="aaa"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="demo2/cyj/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
Student.java
代码:
package demo2.cyj.pojo;
public class Student {
private int id ;
private String stu_name ;
private int stu_age ;
public Student() {}
public Student(int id, String stu_name, int stu_age) {
super();
this.id = id;
this.stu_name = stu_name;
this.stu_age = stu_age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
public int getStu_age() {
return stu_age;
}
public void setStu_age(int stu_age) {
this.stu_age = stu_age;
}
@Override
public String toString() {
return "Student [id=" + id + ", stu_name=" + stu_name + ", stu_age=" + stu_age + "]";
}
}
方法二:通过接口+注解SQL方式来交互数据
在之前的demo项目下新建一个demo3.cyj包用于做接口的实现方式,最终项目结构如下:
最终目录结构
1. 将之前demo中的Student.java复制到相应包下
2. 在config包下新建mybatis_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>
<!-- 配置默认开发环境,default中的值与下面的开发环境id对应 -->
<environments default="development">
<!-- 配置开发环境 -->
<environment id="development">
<!-- JDBC事务 -->
<transactionManager type="JDBC"/>
<!-- 连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="aaa"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
</configuration>
3. 在dao包下新建接口StudentDao.java
,并通过注解配置sql语句:
package demo3.cyj.dao;
import org.apache.ibatis.annotations.Select;
import demo3.cyj.pojo.Student;
public interface StudentDao{
@Select({"select * from student where id = #{id}" })
public Student selectStuById(int id);
}
此时在mybatis_confiig.xml
中添加<mappers></mappers>
的配置,全部代码如下:
<?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对应 -->
<environments default="development">
<!-- 配置开发环境 -->
<environment id="development">
<!-- JDBC事务 -->
<transactionManager type="JDBC" />
<!-- 连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8" />
<property name="username" value="aaa" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="demo3/cyj/dao/StudentDao" />
</mappers>
</configuration>
4. 新建MybatisTest3.java
测试类进行测试
package demo3.cyj;
import java.io.IOException;
import java.io.InputStream;
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 demo3.cyj.dao.StudentDao;
import demo3.cyj.pojo.Student;
public class MybatisTest3 {
public static void main(String[] args) throws IOException {
// mybatis的配置文件的路径
String resource = "demo2/cyj/config/mybatis_config.xml";
// 读取配置文件的路径
InputStream inputStream = Resources.getResourceAsStream(resource);
// 获取到sqlSession的构造工厂类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//在使用注解方式查询时需要注册mapper,相当于还是生成了一个mapper,只不过在开发时可以少写一点
sqlSessionFactory.getConfiguration().addMapper(StudentDao.class);
// 括号内加true,那么会自动提交,否则(括号内不传参)最后要手动提交
SqlSession session = sqlSessionFactory.openSession(true);
StudentDao studentDao = session.getMapper(StudentDao.class);
//在dao中指定了返回的类型是obj还是list,所以就不用特别指定selectOne还是selectList
Student s3 = studentDao.selectStuById(1);
System.out.println(s3);
}
}
运行结果如下:
运行结果
在这种方式中,需要注意的一点是,因为省略了,mapper的xml文件,所以在使用前要注册mapper,具体代码是
sqlSessionFactory.getConfiguration().addMapper(StudentDao.class);
如果没写就会报错:
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface demo3.cyj.dao.StudentDao is not known to the MapperRegistry.
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface demo3.cyj.dao.StudentDao is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:717)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:292)
at demo3.cyj.MybatisTest3.main(MybatisTest3.java:27)
附Student.java
代码:
package demo3.cyj.pojo;
public class Student {
private int id ;
private String stu_name ;
private int stu_age ;
public Student() {}
public Student(int id, String stu_name, int stu_age) {
super();
this.id = id;
this.stu_name = stu_name;
this.stu_age = stu_age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
public int getStu_age() {
return stu_age;
}
public void setStu_age(int stu_age) {
this.stu_age = stu_age;
}
@Override
public String toString() {
return "Student [id=" + id + ", stu_name=" + stu_name + ", stu_age=" + stu_age + "]";
}
}
网友评论