设为首页 收藏本站
查看: 837|回复: 0

[经验分享] MyBatis 初探

[复制链接]

尚未签到

发表于 2016-11-24 04:45:52 | 显示全部楼层 |阅读模式
  话说很早以前就知道ibatis是一个ORM—对象关系映射框架,以前一直使用的是hibernate,所以也没去实际感受一下他的魅力之所在~~现在有个项目用到了MyBatis,所以就特来感受一番。

@@需要准备的jar包:mybatis-3.0.5.jar和sqljdbc.jar


下面开始我们的项目:
1、第一步:建立数据库studentDB,建表StudentInfo,具体的建表语句就不写了,比较简单。

2、第二步:创建工程
  3、第三步:导入jar包(mybatis-3.0.5.jar和sqljdbc.jar)
  4、第四步:编写MyBatis主配置文件—可以自定义名字。我在这里延续ibatis的传统使用SqlMapConfig.xml(类似于hibernate中的hibernate.cfg.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>
<typeAliases>
<typeAlias type="com.up.StudentInfo" alias="StudentInfo"/>
</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=studentDB"/>
<property name="username" value="sa"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="studentMapper.xml"/>
</mappers>
</configuration>
  5、第五步:配置数据库表映射文件:studentMapper.xml(类似于hiberante中的.hbm.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">
<!--这里namespace必须配置为StudentMapper接口的路径,否则运行时会报“is not known to the MapperRegistry”
-->
<mapper namespace="com.up.StudentMapper">
<!-- 这里必须配置resultMap,否则在selectBoy中,将报null错误,无法将数据库中的值注入到StudentInfo类中-->
<resultMap type="StudentInfo" id="boys">
<id property="stuid" column="stuid"/>
<result property="stuname" column="stuname" />
<result property="stusex" column="stusex" />
<result property="stuscore" column="stuscore" />
<result property="stuage" column="stuage" />
</resultMap>
<select id="selectBoy" parameterType="string" resultMap="boys" resultType="arraylist">
select * from StudentInfo where stusex = #{stusex}
</select>
<!--这里的id必须配置和StudentMapper中的方法一样,否则也会报错。下面也一样道理-->
<select id="selectByID" parameterType="int" resultType="StudentInfo">
select * from StudentInfo where stuid = #{stuid}
</select>
<insert id="addStudent" parameterType="StudentInfo" useGeneratedKeys="true">
insert into StudentInfo(stuname,stusex,stuscore,stuage)
values(#{stuname},#{stusex},#{stuscore},#{stuage})
</insert>
<update id="updateStudent" parameterType="StudentInfo">
update StudentInfo
set stuname=#{stuname},stusex=#{stusex},stuscore=#{stuscore}
where stuid=#{stuid}
</update>
<delete id="deleteStudent" parameterType="int">
delete from StudentInfo where stuid = #{stuid}
</delete>
</mapper>
  
6、第六步:编写java代码

  StudentInfo实体类的代码如下:


package com.up;
public class StudentInfo {
private int stuid;
private String stuname;
private String stusex;
private double stuscore;
private int stuage;
public StudentInfo(){
super();
}
public StudentInfo(int stuid,String stuname,String stusex,double stuscore,int stuage){
super();
this.stuid = stuid;
this.stuname = stuname;
this.stusex = stusex;
this.stuscore = stuscore;
this.stuage = stuage;
}
public void setStuid(int stuid) {
this.stuid = stuid;
}
public int getStuid() {
return stuid;
}
public int getStuage() {
return stuage;
}
public String getStuname() {
return stuname;
}
public double getStuscore() {
return stuscore;
}
public String getStusex() {
return stusex;
}
public void setStuage(int stuage) {
this.stuage = stuage;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public void setStuscore(double stuscore) {
this.stuscore = stuscore;
}
public void setStusex(String stusex) {
this.stusex = stusex;
}
public String toString(){
return "学号:"+this.getStuid()+" 姓名:"+this.getStuname()+" 性别:"+this.getStusex()+
" 年龄:"+this.getStuage()+" 分数:"+this.getStuscore();
}
}
   StudentInfo实体的映射器取名为:StudentMapper(接口),其代码如下:


package com.up;
import java.util.ArrayList;
public interface StudentMapper {
//这里的方法对应了studentMapper.xml中的select,update,delete语句
public ArrayList<StudentInfo> selectBoy(String male);
public StudentInfo selectByID(int id);
public void addStudent(StudentInfo student);
public void updateStudent(StudentInfo student);
public void deleteStudent(int id);
}
  注意: 该接口类似于hibernate中的dao层接口,只是该接口只需要声明,不需要实现。
  据我所知:在MyBatis中不声明该接口也是可以的。也许这是一个约定俗成的东西。所以最好定义一下。
  加载配置文件得到SqlSessionFactory工具类代码:


package com.up;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private static final SqlSessionFactory factory;
static {
String resource = "SqlMapConfig.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (Exception e) {
e.printStackTrace();
}
factory = new SqlSessionFactoryBuilder().build(reader);
}
public static SqlSessionFactory getSqlSessionFactory(){
return factory;
}
}
  主要的测试类,该类只是用于测试,所以各方法定义的不是那么灵活,可扩展。

package com.up;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
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;
/**
* 在该类中,主要定义了几个方法,用来测试XML文件中的insert,update,delete,select语句
* addStudent()方法对应了studentMapper.xml中的addStudent操作
* getBoys()方法对应了studentMapper.xml中的selectBoy操作
* getStudent()方法对应了studentMapper.xml中的selectByID操作
* delStudent()方法对应了studentMapper.xml中的deleteStudent操作
* updateStudent()方法对应了studentMapper.xml中的updateStudent操作
*
* @author 小小虾
*
*/
public class TestMybatis {
private static SqlSessionFactory factory = null;
static {
factory = MyBatisUtil.getSqlSessionFactory();
}
public void addStudent(){
SqlSession session = factory.openSession();
StudentInfo student = new StudentInfo();
student.setStuname("王王王");
student.setStuid(00001);
student.setStusex("男");
student.setStuscore(88);
student.setStuage(19);
try {
session.selectOne("StudentMapper.addStudent", student);
session.commit();
} finally {
session.close();
}
}
public void getBoys(){
SqlSession session = factory.openSession();
try {
StudentMapper mapper = session.getMapper(StudentMapper.class);
ArrayList list = mapper.selectBoy("男");
for(int i=0;i<list.size();i++){
StudentInfo stu = (StudentInfo)list.get(i);
System.out.println(stu);
}
} finally {
session.close();
}
}
public void getStudent(){
SqlSession session = factory.openSession();
try {
StudentMapper mapper = session.getMapper(StudentMapper.class);
StudentInfo stu = mapper.selectByID(10018);
System.out.println("信息:"+stu);
} finally {
session.close();
}
}
public void delStudent(){
SqlSession session = factory.openSession();
try {
StudentMapper mapper = session.getMapper(StudentMapper.class);
mapper.deleteStudent(10018);
session.commit();
} finally {
session.close();
}
}
public void updateStudent(){
SqlSession session = factory.openSession();
StudentInfo student = new StudentInfo();
student.setStuname("swu");
student.setStuid(10006);
student.setStusex("女");
student.setStuscore(111);
student.setStuage(100);
try {
StudentMapper mapper = session.getMapper(StudentMapper.class);
mapper.updateStudent(student);
session.commit();
} finally {
session.close();
}
}
public static void main(String[] args) {
TestMybatis m = new TestMybatis();
m.delStudent();
m.getStudent();
}
}
  注意:


try {
StudentMapper mapper = session.getMapper(StudentMapper.class);
mapper.addStudent(student);
} finally {
session.close();
}
  session必须在finally中关闭。

  至此,我的MyBatis初探就告一段落了,在此,要感谢网络上各位大侠。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-304521-1-1.html 上篇帖子: MyBatis缓存 下篇帖子: mybatis配置
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表