myBatis是什么
myBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录.orm工具的基本思想
1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.即得到session工厂
2. 由sessionfactory 产生 session3. 在session 中完成对数据的增删改查和事务提交等.
4. 在用完之后关闭session 。
5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。
搭建开发环境
1.导入jar包
我们使用myBatis需要导入mybatis-3.2.8.jar和 sqljdbc4.jar包,这里导入sqljdbc4.jar是因为我使用的是sql server数据库,如果使用别的数据库请导入别的数据库驱动jar包
2.建立数据库
我使用的是sql server,当然也可以使用其他的数据库
3.配置xml文件
我们使用mybatis需要配置config.xml
<pre name="code" class="html"><?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>
<typeAliases>
<typeAlias alias="User" type="com.ldu.syd.mybatis.User"/>
<typeAlias alias="Content" type="com.ldu.syd.mybatis.Content"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=mybatis" />
<property name="username" value="sa"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ldu/syd/mybatis/User.xml"/>
</mappers>
</configuration>
4.建立数据库映射文件
<pre name="code" class="java">package com.ldu.syd;
public class User {
private String uname;
private String upwd;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
@Override
public String toString() {
return "User [uname=" + uname + ", upwd=" + upwd + "]";
}
}
5.配置映射文件
<pre name="code" class="html"><?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="com.ldu.syd.ss">
<select id="selectUserByName" parameterType="String" resultType="User">
select * from [login] where uname=#{uname}
</select>
</mapper>
配置的映射文件namespace可以随便起,parameterType是对数据库进行操作的条件数据类型。resultType是数据库查询结果的返回类型,这个类型与config.xml配置文件的类的别名有关
6.测试
package com.ldu.syd;
import java.io.IOException;
import java.io.Reader;
import javax.jms.Session;
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 Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Reader reader=Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=(SqlSession) sessionFactory.openSession();
User user=(User)session.selectOne("com.ldu.syd.ss.selectUserByName","admin");
System.out.println(user);
}
}
面向接口的使用
java是面向接口的编程,我们也可使用面向接口的方式使用mybatis1.定义接口
package com.ldu.syd.mybatis;
import java.util.List;
public interface IUser {
public User selectUserById(int id);
public List<User> selectUserAll();
}
2.我们需要重新配置映射文件
<?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="com.ldu.syd.mybatis.IUser">
<select id="selectUserById" parameterType="int" resultType="User">
select * from [user] where id=#{id}
</select>
<resultMap type="User" id="userResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
</resultMap>
<select id="selectUserAll" resultMap="userResult">
select * from [user]
</select>
</mapper>
注意:面向接口的使用,namespace必须是接口的全路径。即包名+接口名。对数据库的增删改查的id必须与接口的函数名把持一致。其他的地方与不同的使用无区别。
3.测试
package com.ldu.syd.mybatis;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import javax.jms.Session;
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 main {
/**
* @param args
*/
public static void main(String[] args) {
try {
Reader reader=Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=sqlSessionFactory.openSession();
IUser iUser=(IUser) session.getMapper(IUser.class);
User user=iUser.selectUserById(1);
List<User> list=iUser.selectUserAll();
System.out.println(user);
for(User u:list){
System.out.println(u);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
}
}
}
多表级联查询
1.建立数据库
2.建立数据库表的映射文件
package com.ldu.syd.mybatis;
public class Content {
private int id;
private User user;
private String title;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Content [id=" + id + ", user=" + user + ", title=" + title
+ "]";
}
}
package com.ldu.syd.mybatis;
public class User {
private int id;
private String name;
private String sex;
private String age;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age="
+ age + "]";
}
}
3.
配置映射文件
<?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="com.ldu.syd.mybatis.IUser">
<resultMap type="Content" id="ContentResult">
<id property="id" column="id" />
<result property="title" column="title" />
<association property="user" javaType="User">
<id property="id" column="id" />
<result property="sex" column="sex" />
<result property="age" column="age" />
</association>
</resultMap>
<select id="selectUserById" parameterType="int" resultMap="ContentResult">
select * from user_a a,content b where a.id=b.uid and a.id=#{id}
</select>
</mapper>
注:resultMap 是映射对应关系
4.测试
package com.ldu.syd.mybatis;
import java.io.IOException;
import java.io.Reader;
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;
public class main {
/**
* @param args
*/
public static void main(String[] args) {
try {
Reader reader=Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sesionFactory=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=sesionFactory.openSession();
IUser iUser=session.getMapper(IUser.class);
List<Content> list=iUser.selectUserById(1);
System.out.println(list.size());
for(Content c:list){
System.out.println(c);
}
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这只是简单的使用,适合刚学习得人使用