1. First step. Deploy mybatis;
1.1 Download myBatis
MyBits predecessor is iBitis, which is a semi-automated ORM framework relative to Hibernate. Because of the strict performance requirements of the boss, I had to abandon my dear hibernate to learn and use mybatis. Before that, I was not familiar with mybatis. If there are any mistakes, please correct them. I hope it will be helpful for my classmates who want to learn mybitis.
Given that my test database is mysql, my colleagues now install mysql, then prepare the MySQL driver and download mybitis( http://code.google.com/p/mybatis/).
I used maven. I wrote it directly in the pom file.
<dependencies> <!-- db --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.5</version> </dependency> <!-- join mysql Driver dependency packages --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency>
2. New Data Table
DROP TABLE IF EXISTS `t_test`; CREATE TABLE `t_test` ( `id` int(11) NOT NULL, `userName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_test -- ---------------------------- INSERT INTO `t_test` VALUES ('1', '2');
3. use mybatis-generator Automatically generate code
Create a configuration file, such as conf.xml, where the name of the file is named by itself. There is no special requirement for naming. You can refer to the configuration file in the doc document. My name is as follows
<?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> <!-- Database Driven Package Location --> <!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> --> <classPathEntry location="E:\data\.m2\repository\mysql\mysql-connector-java\5.1.25\mysql-connector-java-5.1.25.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- Database Links URL,User name, password --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/c_sai" userId="root" password=""> <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">--> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- Package name and location of the generated model --> <javaModelGenerator targetPackage="com.test.model" targetProject="F:\source"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- Generated mapping file package name and location --> <sqlMapGenerator targetPackage="com.test.mapping" targetProject="F:\source"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- generate DAO The package name and location of --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.dao" targetProject="F:\source"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- To generate those tables(change tableName and domainObjectName Can) --> <table tableName="t_test" domainObjectName="TTest" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> </context> </generatorConfiguration>
Executing jar files
E:\data\Users\Administrator\Downloads\generator> java -jar mybatis-generator-cor e-1.3.2.jar -configfile generator.xml -overwrite MyBatis Generator finished successfully.
The generated code is as follows
package com.test.model; public class TTest { private Integer id; private String username; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } }
package com.test.dao; import com.test.model.TTest; public interface TTestMapper { int deleteByPrimaryKey(Integer id); int insert(TTest record); int insertSelective(TTest record); TTest selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(TTest record); int updateByPrimaryKey(TTest record); }
XML is as follows
<?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="com.test.dao.TTestMapper" > <resultMap id="BaseResultMap" type="com.test.model.TTest" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="userName" property="username" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, userName </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from t_test where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from t_test where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.test.model.TTest" > insert into t_test (id, userName) values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.test.model.TTest" > insert into t_test <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="username != null" > userName, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="username != null" > #{username,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.test.model.TTest" > update t_test <set > <if test="username != null" > userName = #{username,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.test.model.TTest" > update t_test set userName = #{username,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper>
Write mybatis configuration file
mybatis-config.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> <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://127.0.0.1:3306/c_sai" /> <property name="username" value="root" /> <property name="password" value="" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com\test\mapping\TTestMapper.xml" /> </mappers> </configuration>
Writing test classes
package com.jefry; import java.io.IOException; import java.io.InputStream; 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 com.test.model.TTest; public class Test { static String resource = "mybatis-config.xml"; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { // User.selectUser in User Corresponding UserMapper.xml Document label<mapper // namespace="com.test.dao.TTestMapper"> namespace Value // selectUser Corresponding UserMapper.xml Document label<select id="selectUser" // parameterType="int" resultType="com.jefry.User">in id value TTest tt = session.selectOne("com.test.dao.TTestMapper.selectByPrimaryKey", 1); System.out.println("tt.getName()=" + tt.getUsername()); } finally { session.close(); } } }
Result:
tt.getName()=2
So far mybatis has been deployed successfully.
Reproduced in: https://my.oschina.net/u/1590001/blog/268237