话说很早以前就知道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初探就告一段落了,在此,要感谢网络上各位大侠。