Spring+mybatis的一个简单例子
jopen
9年前
一、eclipse新建java项目取名SpringTest
二、倒入sping,mybatis,jdbc(这里用postgresql)包到构建路径
三、在psql中建库、建表的脚本。
CREATE DATABASE mymotif WITH OWNER = mymotif ENCODING = 'UTF8' TABLESPACE = mymotif_ts LC_COLLATE = 'zh_CN.UTF-8' LC_CTYPE = 'zh_CN.UTF-8' CONNECTION LIMIT = -1; CREATE TABLE student ( sno character(7) NOT NULL, sname character(8) NOT NULL, sex character(2) NOT NULL, bdate date, dir character(16), CONSTRAINT student_pkey PRIMARY KEY (sno) ) WITH ( OIDS=FALSE ); ALTER TABLE student OWNER TO mymotif;
四、创建java类
student表对应的pojo对象
package cn.itcast.mybatis.domain; import java.sql.Date; public class Student { private String SNO; private String SNAME; private String SEX; private Date BDATE; private String DIR; public Student() { } public Student(String id, String name, String sex,Date date , String dir) { this.SNO = id; this.SNAME = name; this.SEX = sex; this.DIR = dir; this.BDATE=date; } public String getDIR() { return DIR; } public void setDIR(String dir) { this.DIR = dir; } public String getSNO() { return SNO; } public void setSNO(String sno) { this.SNO = sno; } public String getSNAME() { return SNAME; } public void setSNAME(String name) { this.SNAME = name; } public String getSEX() { return SEX; } public void setSEX(String sEX) { SEX = sEX; } public Date getBDATE() { return BDATE; } public void setBDATE(Date bDATE) { BDATE = bDATE; } @Override public String toString() { return "Student [sno=" + SNO + ", name=" + SNAME + ", sex=" + SEX+ ", birthday=" + BDATE + ", direction=" + DIR + "]"; } }
映射文件cn/itcast/mybatis/domain/Student.xml(和pojo对象在一个包内)
<?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="cn.itcast.mybatis.domain.Student"> <sql id="cols"> SNO,SNAME,SEX,BDATE,DIR </sql> <sql id="ucols"> SNO=#{SNO},SNAME=#{SNAME},SEX=#{SEX},BDATE=#{BDATE},DIR=#{DIR} </sql> <!-- 查询所有记录 --> <select id="listAll" resultType="aliasesStudent"> select <include refid="cols" /> from STUDENT </select> <!-- 按条件查询 --> <select id="find" parameterType="aliasesStudent" resultType="aliasesStudent"> select * from STUDENT <where> <if test="SNAME!=null"> and name like "%"#{SNAME}"%" </if> <if test="BDATE!=null"> and age=#{BDATE} </if> <if test="DIR!=null"> and age=#{DIR} </if> </where> </select> <!-- 查询一个用户 --> <select id="get" parameterType="string" resultType="aliasesStudent"> select <include refid="cols" /> from STUDENT where SNO=#{SNO} </select> <!-- 新增 --> <insert id="create" parameterType="aliasesStudent"> insert into STUDENT (SNO,SNAME,SEX,BDATE,DIR) values(#{SNO},#{SNAME},#{SEX},#{BDATE},#{DIR}) </insert> <!-- 修改 --> <update id="update" parameterType="aliasesStudent"> update STUDENT <set> <if test="SNAME!=null"> SNAME=#{SNAME}, </if> <if test="BDATE!=null"> BDATE=#{BDATE}, </if> <if test="DIR!=null"> DIR=#{DIR}, </if> </set> where SNO=#{SNO} </update> <!-- 删除 --> <delete id="delete" parameterType="string"> delete from STUDENT where SNO=#{SNO} </delete> </mapper>
对Student对象的访问接口及实现类
package cn.itcast.mybatis.dao; import java.util.List; import cn.itcast.mybatis.domain.Student; public interface IStudentDao { public List<Student> list(); public Student get(String SNO); public int insert(Student S); public int update(Student S); public int deleteById(String SNO); }
package cn.itcast.mybatis.dao; import java.util.List; import org.mybatis.spring.support.SqlSessionDaoSupport; import cn.itcast.mybatis.domain.Student; public class StudentDaoImpl extends SqlSessionDaoSupport implements IStudentDao { @Override public List<Student> list() { // TODO 自动生成的方法存根 return this.getSqlSession().selectList("cn.itcast.mybatis.domain.Student.listAll"); } @Override public Student get(String SNO) { // TODO 自动生成的方法存根 return (Student) this.getSqlSession().selectOne("cn.itcast.mybatis.domain.Student.get", SNO); } @Override public int insert(Student S) { // TODO 自动生成的方法存根 return this.getSqlSession().insert("cn.itcast.mybatis.domain.Student.create", S); } @Override public int update(Student S) { // TODO 自动生成的方法存根 return this.getSqlSession().update("cn.itcast.mybatis.domain.Student.update",S); } @Override public int deleteById(String SNO) { // TODO 自动生成的方法存根 return this.getSqlSession().delete("cn.itcast.mybatis.domain.Student.delete",SNO); } }
五、配置文件
resources/psqlStudentMapConfig.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="cn.itcast.mybatis.domain.Student" alias="aliasesStudent"></typeAlias> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.postgresql.Driver"/> <property name="url" value="jdbc:postgresql:mymotif"/> <property name="username" value="mymotif"/> <property name="password" value="passwd"/> </dataSource> </environment> <!-- 产品 可用于多个配置的 --> <environment id="product"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.postgresql.Driver"/> <property name="url" value="jdbc:postgresql:mymotif"/> <property name="username" value="mymotif"/> <property name="password" value="passwd"/> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/itcast/mybatis/domain/Student.xml"/> </mappers> </configuration>
resources/psql-beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.postgresql.Driver"></property> <property name="url" value="jdbc:postgresql:mymotif"></property> <property name="username" value="mymotif"></property> <property name="password" value="passwd"></property> </bean> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:resources/psqlStudentMapConfig.xml"></property> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 事务相关控制 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="StudentDao" class="cn.itcast.mybatis.dao.StudentDaoImpl"> <property name="sqlSessionFactory" ref="sessionFactory"></property> </bean> </beans>
六、测试类
package cn.itcast.mybatis.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.mybatis.dao.IStudentDao; import cn.itcast.mybatis.domain.Student; public class TestpStudentMybatis { /** * @param args */ private static ApplicationContext cxt; public static void main(String[] args) { // TODO 自动生成的方法存根 cxt = new ClassPathXmlApplicationContext("resources/psql-beans.xml"); IStudentDao sd = (IStudentDao) cxt.getBean("StudentDao"); List<Student> students = sd.list(); System.out.println("STUDENT表的记录数为:" + students.size()); for (int i = 0; i < students.size(); i++) System.out.println(students.get(i).toString()); } }
运行结果:
数据库改为mysql,只需改变配置文件如下
<?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="cn.itcast.mybatis.domain.Student" alias="aliasesStudent"></typeAlias> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb?characterEncoding=UTF-8"/> <property name="username" value="mymotif"/> <property name="password" value="passwd"/> </dataSource> </environment> <!-- 产品 可用于多个配置的 --> <environment id="product"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb?characterEncoding=UTF-8"/> <property name="username" value="mymotif"/> <property name="password" value="passwd"/> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/itcast/mybatis/domain/Student.xml"/> </mappers> </configuration>