mybatis基本的增删改查实现 博客分类: MyBatis Mybatishelloworld
程序员文章站
2024-03-18 15:16:28
...
准备基本jar包
mybatis-3.0.5.jar,
mysql-connector-java-xxx.jar
表对象User,包含id,name,age,getset、toString方法。
mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!-- iBatis 和 MyBatis 的全局配置文件使用不同的 DTD 约束,在将应用由 iBatis 升级至 MyBatis 时需要注意(两者的映射文件 DTD 约束也不相同) --> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- 这是根标签 --> <configuration> <!-- 元素允许在主配置文件之外提供一个properties格式对应文件,从而使得主配置文件更加通用。这样对部署非常有用 --> <!--当加入第二个配置文件的时候编译器报错--> <properties resource="db.properties" /> <typeAliases> <typeAlias alias="User" type="study.renk.pojo.User" /> </typeAliases> <!-- 配置数据源相关的信息 --> <!--同时使用过access做的配置,将mysql_修改为access_就可以了--> <environments default="demo"> <environment id="demo"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${mysql_driver}"/> <property name="url" value="${mysql_url}" /> <property name="username" value="${mysql_username}" /> <property name="password" value="${mysql_password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="study/renk/mapper/user.xml"/> </mappers> </configuration>
数据库配置文件db.properties
mysql_driver = com.mysql.jdbc.Driver mysql_url = jdbc:mysql://127.0.0.1:3306/zrk_test mysql_username = root mysql_password =1234 access_driver = sun.jdbc.odbc.JdbcOdbcDriver access_url = jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=E:/db.mdb access_username = db access_password =acms_123
User.xml mybatis的操作映射文件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 指向接口,接口中声明以ID命名的方法,参数和返回对象类型保持和配置文件中一致 --> <!-- 通过UserMapper um = sqlSession.getMapper(UserMapper.class);获取对象后,可直接调用 --> <mapper namespace="study.renk.dao.UserMapper"> <select id="selectUser" parameterType="int" resultType="User"> <!-- CDATA说明,指定CDATA内信息不会被解析器解析,比如sql中出现大于小于时 --> <![CDATA[ select * from t_zrk_user where id = #{id} ]]> </select> <select id="selectByCondition" parameterType="User" resultType="User"> <![CDATA[ select * from t_zrk_user where 1=1 ]]> <if test="name!=null and name!=''"> <![CDATA[ and name like CONCAT('%',#{name},'%') ]]> </if> <if test="age!=null and age!=''"> <![CDATA[ and age = #{age} ]]> </if> </select> <insert id="insertUser" parameterType="User"> insert into t_zrk_user (id,name,age) values(#{id},#{name},#{age}) </insert> <!-- 此方法的foreach,在使用access时,会提示出错。 在使用批量插入时,一定得测试数据库是否支持 --> <insert id="insertBatchUser" parameterType="java.util.List"> insert into t_zrk_user (id,name,age) values <foreach collection="list" item="item" index="index" separator="," > (#{item.id},#{item.name},#{item.age}) </foreach> </insert> </mapper>
在此处着重说明下批量更新操作。
使用access做批量插入时,系统直接报错,不支持此批量操作,换到mysql时,就正常了。
UserMapper映射接口
package study.renk.dao; import java.util.List; import study.renk.pojo.User; public interface UserMapper { User selectUser(String id); List selectByCondition(User user); void insertUser(User user); void insertBatchUser(List<User> list); }
调用Main.java
package study.renk.domain; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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 study.renk.dao.UserMapper; import study.renk.pojo.User; public class Main { private static final Log logger = LogFactory.getLog(Main.class); private UserMapper um; public UserMapper getUm() { return um; } public void setUm(UserMapper um) { this.um = um; } public static void main(String[] args) throws IOException { // 获取配置文件的输入流 InputStream is = Resources.getResourceAsStream("mybatis.xml"); // 获取我们的SqlSessionFactory(相当于Hibernate的SessionFactory); //SqlSessionFactoryBuilder有点类似于Hibernate的Configuration。 SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is); // 获取一个Session SqlSession ss = ssf.openSession(); UserMapper um = ss.getMapper(UserMapper.class); // User user = um.selectUser("2013073101"); // System.out.println(user); // User condition = new User(); // condition.setName("哈哈"); long b_t = System.currentTimeMillis(); List<User> list = new ArrayList<User>(); for(int i=0;i<10000;i++){ User user = new User(); user.setId(1308010000+i+""); user.setName("Name"+(10000+i)); // if(i == 3) // user.setAge(15+i+"aa"); // else user.setAge(15+i+""); list.add(user); //10000条记录插入耗时:13819ms // um.insertUser(user); } //10000条记录插入耗时:2344ms um.insertBatchUser(list); System.out.println("插入用时:====>"+ (System.currentTimeMillis()-b_t)+"ms"); try{ //下面的ss.select 此类,需要把user.xml中namespace修改为User // t.commit(); // User user = (User)ss.selectOne("User.selectUser","2013072901"); // System.out.println(user); // Map map = ss.selectMap("User.selectByCondition",condition,"id"); // System.out.println(map.get("2013072901")); // List list = ss.selectList("User.selectByCondition",condition); // for(int i=0;i<list.size();i++){ // logger.info(list.get(i)); // } }catch(Exception e){ ss.close(); e.printStackTrace(); } } }