我在eclipse新建java project项目。然后建了两个包:org.mybatis.example和org.mybatis.javabean
第一个包用来放测试类和映射文件。
第二个包用来放数据库相对应的javaBean。
然后,在数据库里建立表:
-- Table "t_user" DDL CREATE TABLE `t_user` ( `user_name` varchar(20) NOT NULL default '', `password` varchar(20) default NULL, PRIMARY KEY (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
必须导入的包:
mybatis-3.1.1.jar
mysql-connector-java-5.1.16-bin.jar(这个看你要连接什么数据库了)
另外,为了在测试的时候,能看到执行的SQL语句,我把log4j的包也导入了:
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
log4j-1.2.16.jar
还要加上log4j.properties配置文件:
log4j.properties:
log4j.rootLogger=DEBUG,CONSOLE log4j.addivity.org.apache=true # 应用于控制台 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.Threshold=DEBUG log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n #log4j.appender.CONSOLE.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[thread] n%c[CATEGORY]%n%m[MESSAGE]%n%n
放在了src/java/main目录下
新建mybatis-config.xml文件,放在src/java/main目录下,内如:
<?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> <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/test"/> <property name="username" value="root"/> <property name="password" value="1234"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/TUserMapper.xml"/> </mappers> </configuration>
其中,mapper标签,指向的是一个映射文件。如果你有多个文件,这里可以写多个。
在org.mabatis.example下新建TUserMapper.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"> <mapper namespace="TUser"> <!-- 如果表字段和javaBean名称不一样,可以通过这样的映射来解决 --> <resultMap type="org.mybatis.javabean.TUser" id="ttuser"> <result property="userName" column="user_name" /> <result property="password" column="password" /> </resultMap> <!-- 直接通过map或者javabean插入数据 --> <insert id="insert" parameterType="org.mybatis.javabean.TUser"> insert into t_user(user_name,password) values( #{userName}, #{password} ) </insert> <!-- 更新 --> <update id="update" parameterType="org.mybatis.javabean.TUser"> update t_user <set> <if test="userName!=null">user_name=#{userName},</if> <if test="password!=null">password=#{password}</if> </set> <where> <if test="userName!=null">user_name=#{userName}</if> </where> </update> <!-- 删除 --> <delete id="delete" parameterType="Map"> delete from t_user <where> <if test="userName!=null">user_name=#{userName}</if> </where> </delete> <!-- 查询总数据条数 --> <select id="selectCount" parameterType="Map" resultType="int"> select count(*) from t_user </select> <!-- 按条件查询 --> <select id="select" resultMap="ttuser" parameterType="Map"> select * from t_user <include refid="selectOption"/> </select> <!-- 多条件查询语句 --> <sql id="selectOption"> <where> <if test="userName!=null">user_name=#{userName}</if> <if test="password!=null">and password=#{password}</if> </where> </sql> </mapper>
每个sql语句等,我都写了注释,应该都算清楚了吧。单表的CRUD,这些掌握就足够使用了。
在org.mybatis.example下新建测试类Main,内容如下:
package org.mybatis.example; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; 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 org.mybatis.javabean.TUser; public class Main { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream in = Resources.getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 插入 HashMap<String, String> map = new HashMap<String, String>(); map.put("userName", "lisa"); map.put("password", "100100"); System.out.println("通过map插入结果:" + insert(factory.openSession(), map)); // TUser user = new TUser(); // user.setUserName("lili"); // user.setPassword("abc001"); // System.out.println("通过javabean插入结果:" + insert(factory.openSession(), user)); // 更新 // HashMap<String, String> map = new HashMap<String, String>(); // map.put("userName", "lisa"); // map.put("password", "990099"); // System.out.println("通过map更新结果:" + update(factory.openSession(), map)); // TUser user = new TUser(); // user.setUserName("lili"); // user.setPassword("001100"); // System.out.println("通过javabean更新结果:" + update(factory.openSession(), user)); // 删除 // String userName = "lisa"; // System.out.println("删除结果:" + delete(factory.openSession(), null)); // 查询 // System.out.println("查询总数据条数:" + selectCount(factory.openSession())); // TUser u = new TUser(); // u.setUserName("lisa"); // List<TUser> list = selectList(factory.openSession(), u); // for (TUser user : list) { // System.out.println("name=" + user.getUserName() + ";pwd=" + user.getPassword()); // } } /** * * DOC 通过map或者javaBean插入. * * @param sqlSession * @param map * @return */ private static boolean insert(SqlSession sqlSession, Object mapOrJavaBean) { int i = sqlSession.insert("TUser.insert", mapOrJavaBean); sqlSession.commit(); return i > 0; } /** * * DOC 通过map或javaBean更新信息. * * @param sqlSession * @param map * @return */ private static boolean update(SqlSession sqlSession, Object mapOrJavaBean) { int i = sqlSession.update("TUser.update", mapOrJavaBean); sqlSession.commit(); return i > 0; } /** * * DOC 删除. * * @param sqlSeesion * @param userName * @return */ private static boolean delete(SqlSession sqlSession, String userName) { Map map = new HashMap(); map.put("userName", userName); int i = sqlSession.delete("TUser.delete", map); sqlSession.commit(); return i > 0; } /** * * DOC 查询总数据条数. * * @param sqlSession * @return */ private static int selectCount(SqlSession sqlSession) { return sqlSession.selectOne("TUser.selectCount"); } /** * * DOC 按条件查询. * * @param sqlSession * @param mapOrJavaBean * @return */ private static List<TUser> selectList(SqlSession sqlSession, Object mapOrJavaBean) { return sqlSession.selectList("TUser.select", mapOrJavaBean); } }
最后,放一张项目结构图:
如果你还没工具的话,可以去官网下载。我的前两篇文章里有写到下载地址,可以去看看。
下载好后,解压到某个目录。我解压的是到F盘
将数据库驱动jar包,考入到lib目录下
新建java文件夹
编写配置文件config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <classPathEntry location="mysql-connector-java-5.1.16-bin.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/test" userId="root" password="1234"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="test.model" targetProject="java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="test.dao" targetProject="java"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="test.dao" targetProject="java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <table tableName="t_user" domainObjectName="TUser"> </table> </context> </generatorConfiguration>
命令行下执行:
看到successfully后,则可看到生成的文件