码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis配置

时间:2017-11-26 00:49:22      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:实例   技术   tcl   技术分享   创建   jdbc   inpu   temp   tis   

 

下载网址  :   https://github.com/mybatis/mybatis-3/releases

技术分享图片

 第一个是架包,第二个是源码;

技术分享图片

根据.pdf文件(官方文档配置java工程)

技术分享图片

技术分享图片
 1 package com.tzy.mybatis;
 2 
 3 public class Employee {
 4 private Integer id;
 5 private String lastName;
 6 private String email;
 7 private String gender;
 8 public Integer getId() {
 9     return id;
10 }
11 public void setId(Integer id) {
12     this.id = id;
13 }
14 public String getLastName() {
15     return lastName;
16 }
17 public void setLastName(String lastName) {
18     this.lastName = lastName;
19 }
20 public String getEmail() {
21     return email;
22 }
23 public void setEmail(String email) {
24     this.email = email;
25 }
26 public String getGender() {
27     return gender;
28 }
29 public void setGender(String gender) {
30     this.gender = gender;
31 }
32 @Override
33 public String toString() {
34     return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";
35 }
36 
37 }
Employee.java
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <environments default="development">
 7         <environment id="development">
 8             <transactionManager type="JDBC" />
 9             <dataSource type="POOLED">
10                 <property name="driver" value="com.mysql.jdbc.Driver" />
11                 <property name="url" value="jdbc:mysql:///mybatis" />
12                 <property name="username" value="root" />
13                 <property name="password" value="root" />
14             </dataSource>
15         </environment>
16     </environments>
17     
18     <!-- 将自己的SQL映射文件配置到全局里 -->
19     <mappers>
20         <mapper resource="EmployeeMapper.xml" />
21     </mappers>
22 </configuration>
mybatis-config.xml
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.tzy.mybatis.EmployeeMapper">
 6     <select id="selectEmp" resultType="com.tzy.mybatis.Employee">
 7         select * from tbl_employee where id = #{id}
 8     </select>
 9     <select id="selectEmp1" resultType="com.tzy.mybatis.Employee">
10         select id,last_name lastName,gender,email from tbl_employee where id = #{id}
11     </select>
12 </mapper>
EmployeeMapper.xml
技术分享图片
 1 package com.tzy.mybatis.test;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 import org.junit.Test;
11 
12 import com.tzy.mybatis.Employee;
13 
14 public class MyBatisTest {
15     
16     /**
17      * 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
18      * @throws IOException
19      */
20     @Test
21     public void test() throws IOException {
22         String resource = "mybatis-config.xml";
23         InputStream inputStream = Resources.getResourceAsStream(resource);
24         SqlSessionFactory sqlSessionFactory =
25         new SqlSessionFactoryBuilder().build(inputStream);
26         
27         //获取sqlSession实例,能直接执行已经映射的sql语句
28         SqlSession openSession = sqlSessionFactory.openSession();
29         
30         try {
31             Employee employee = openSession.selectOne("com.tzy.mybatis.EmployeeMapper.selectEmp", 1);
32             Employee employee1 = openSession.selectOne("com.tzy.mybatis.EmployeeMapper.selectEmp1", 1);
33             
34             System.out.println(employee);
35             System.out.println(employee1);
36         } catch (Exception e) {
37             e.printStackTrace();
38         }finally{
39             openSession.close();
40         }
41         
42         
43     }
44 
45 }
MyBatisTest.java

运行结果:

技术分享图片

 现在mybatis是用接口式编程,故修改上面的代码

技术分享图片

技术分享图片
 1 package com.tzy.mybatis;
 2 
 3 public class Employee {
 4 private Integer id;
 5 private String lastName;
 6 private String email;
 7 private String gender;
 8 public Integer getId() {
 9     return id;
10 }
11 public void setId(Integer id) {
12     this.id = id;
13 }
14 public String getLastName() {
15     return lastName;
16 }
17 public void setLastName(String lastName) {
18     this.lastName = lastName;
19 }
20 public String getEmail() {
21     return email;
22 }
23 public void setEmail(String email) {
24     this.email = email;
25 }
26 public String getGender() {
27     return gender;
28 }
29 public void setGender(String gender) {
30     this.gender = gender;
31 }
32 @Override
33 public String toString() {
34     return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";
35 }
36 
37 }
Employee.java
技术分享图片
1 package com.tzy.mybatis.dao;
2 
3 import com.tzy.mybatis.Employee;
4 
5 public interface EmployeeMapper {
6 public Employee getEmpById(Integer id);
7 }
接口EmployeeMapper.java
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.tzy.mybatis.dao.EmployeeMapper">
 6 <!-- namespace命名空间;指定为接口的全类名,就实现了动态绑定 -->
 7     <select id="selectEmp" resultType="com.tzy.mybatis.Employee">
 8         select * from tbl_employee where id = #{id}
 9     </select>
10     <select id="selectEmp1" resultType="com.tzy.mybatis.Employee">
11         select id,last_name lastName,gender,email from tbl_employee where id = #{id}
12     </select>
13     <!-- select方法id和接口方法名一致,动态绑定
14     public Employee getEmpById(Integer id); -->
15     <select id="getEmpById" resultType="com.tzy.mybatis.Employee">
16         select id,last_name lastName,gender,email from tbl_employee where id = #{id}
17     </select>
18 </mapper>
EmployeeMapper.xml
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <environments default="development">
 7         <environment id="development">
 8             <transactionManager type="JDBC" />
 9             <dataSource type="POOLED">
10                 <property name="driver" value="com.mysql.jdbc.Driver" />
11                 <property name="url" value="jdbc:mysql:///mybatis" />
12                 <property name="username" value="root" />
13                 <property name="password" value="root" />
14             </dataSource>
15         </environment>
16     </environments>
17     
18     <!-- 将自己的SQL映射文件配置到全局里 -->
19     <mappers>
20         <mapper resource="EmployeeMapper.xml" />
21     </mappers>
22 </configuration>
mybatis-config.xml
技术分享图片
 1 package com.tzy.mybatis.test;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 import org.junit.Test;
11 
12 import com.tzy.mybatis.Employee;
13 import com.tzy.mybatis.dao.EmployeeMapper;
14 
15 public class MyBatisTest {
16 
17     public SqlSessionFactory getSqlSessionFactory() throws IOException {
18         String resource = "mybatis-config.xml";
19         InputStream inputStream = Resources.getResourceAsStream(resource);
20         return new SqlSessionFactoryBuilder().build(inputStream);
21     }
22 
23     /**
24      * 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
25      * 
26      * @throws IOException
27      */
28     @Test
29     public void test() throws IOException {
30         SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
31 
32         // 获取sqlSession实例,能直接执行已经映射的sql语句
33         SqlSession openSession = sqlSessionFactory.openSession();
34 
35         try {
36             Employee employee = openSession.selectOne("com.tzy.mybatis.EmployeeMapper.selectEmp", 1);
37             Employee employee1 = openSession.selectOne("com.tzy.mybatis.EmployeeMapper.selectEmp1", 1);
38 
39             System.out.println(employee);
40             System.out.println(employee1);
41         } catch (Exception e) {
42             e.printStackTrace();
43         } finally {
44             openSession.close();
45         }
46     }
47 
48     //获取接口的实现类对象,会为接口自动的创建一个代理对象,代理对象会去执行增删改查
49     @Test
50     public void test1() throws IOException {
51         SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
52         SqlSession openSession = sqlSessionFactory.openSession();
53 
54         try {
55             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
56             System.out.println(mapper.getClass());
57             Employee employee = mapper.getEmpById(1);
58             System.out.println(employee);
59         } catch (Exception e) {
60             e.printStackTrace();
61         } finally {
62             openSession.close();
63         }
64     }
65 
66 }
MyBatisTest

运行测试一结果:

 技术分享图片

 注意:

1、接口式变成

原生:    Dao====> DaoImpl

mybatis:   Mapper =====>xxMapper.xml

2、SqlSession代表和数据库的一次会话:用完必须关闭;

3、SqlSession和connection一样它都是非线程安全。每次使用都应该去获取新的对象。

4、mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。(截接口和xml经行绑定)

  sqlSession.getMapper(EmployeeMapper.Class)这个方法就会返回代理

5、两个重要的配置文件:

  mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息。

  sql映射文件:保存了每一个sql语句的映射信息:将sql抽取出来。

 

 

导入dtd约束:找到以下目录解压出来.

技术分享图片

 

老样子三部曲,添加约束

技术分享图片

 

 全局配置文件参考文档

技术分享图片

 基本操作增删改

技术分享图片

技术分享图片
 1 package com.tzy.mybatis;
 2 
 3 public class Employee {
 4 private Integer id;
 5 private String lastName;
 6 private String email;
 7 private String gender;
 8 public Integer getId() {
 9     return id;
10 }
11 public void setId(Integer id) {
12     this.id = id;
13 }
14 public String getLastName() {
15     return lastName;
16 }
17 public void setLastName(String lastName) {
18     this.lastName = lastName;
19 }
20 public String getEmail() {
21     return email;
22 }
23 public void setEmail(String email) {
24     this.email = email;
25 }
26 public String getGender() {
27     return gender;
28 }
29 public void setGender(String gender) {
30     this.gender = gender;
31 }
32 @Override
33 public String toString() {
34     return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";
35 }
36 public Employee(Integer id, String lastName, String email, String gender) {
37     super();
38     this.id = id;
39     this.lastName = lastName;
40     this.email = email;
41     this.gender = gender;
42 }
43 public Employee() {
44     super();
45 }
46 
47 }
Employee
技术分享图片
 1 package com.tzy.mybatis.dao;
 2 
 3 import com.tzy.mybatis.Employee;
 4 
 5 public interface EmployeeMapper {
 6     public Employee getEmpById(Integer id);
 7 
 8     public void addEmp(Employee employee);
 9 
10     public void updateEmp(Employee employee);
11 
12     public void deleteEmpId(Integer id);
13 
14 }
EmployeeMapper
技术分享图片
 1 package com.tzy.mybatis.test;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10 import org.junit.Test;
11 
12 import com.tzy.mybatis.Employee;
13 import com.tzy.mybatis.dao.EmployeeMapper;
14 
15 public class MyBatisTest {
16 
17     public SqlSessionFactory getSqlSessionFactory() throws IOException {
18         String resource = "mybatis-config.xml";
19         InputStream inputStream = Resources.getResourceAsStream(resource);
20         return new SqlSessionFactoryBuilder().build(inputStream);
21     }
22 
23     /**
24      * 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
25      * 
26      * @throws IOException
27      */
28 
29     //mybatis允许直接定义这些类型的返回值:Integer,Long,Boolean
30     //需要手动提交数据
31     @Test
32     public void test2() throws IOException {
33         SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
34         SqlSession openSession = sqlSessionFactory.openSession();
35         try {
36             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
37             Employee employee = new Employee(2, "jjjjerry", "asd@qq.com", "0");
38             //mapper.addEmp(employee);
39             
40             mapper.updateEmp(employee);
41             
42             //mapper.deleteEmpId(1);
43             
44             //增删改要提交
45             openSession.commit();
46         } finally {
47             openSession.close();
48         }
49     
50     }
51 }
MyBatisTest
技术分享图片
1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql:///mybatis
3 jdbc.username=root
4 jdbc.password=root
dbconfig.properties
技术分享图片
 1 #
 2 # Hibernate, Relational Persistence for Idiomatic Java
 3 #
 4 # License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 5 # See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 6 #
 7 
 8 ### direct log messages to stdout ###
 9 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
10 log4j.appender.stdout.Target=System.out
11 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
12 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
13 
14 ### direct messages to file hibernate.log ###
15 #log4j.appender.file=org.apache.log4j.FileAppender
16 #log4j.appender.file.File=hibernate.log
17 #log4j.appender.file.layout=org.apache.log4j.PatternLayout
18 #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
19 
20 ### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###
21 log4j.rootLogger=DEBUG, stdout    
22     
23   
24     
25 #log4j.appender.R=org.apache.log4j.DailyRollingFileAppender    
26 #log4j.appender.R.File=../logs/service.log    
27 #log4j.appender.R.layout=org.apache.log4j.PatternLayout    
28 #log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n    
29     
30 #log4j.logger.com.ibatis = debug    
31 #log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug    
32 #log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug    
33 #log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug    
34 #log4j.logger.java.sql.Connection = debug    
35 log4j.logger.java.sql.Statement = debug    
36 log4j.logger.java.sql.PreparedStatement = debug    
37 log4j.logger.java.sql.ResultSet =debug    
log4j.properties
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.tzy.mybatis.dao.EmployeeMapper">
 6 <!-- namespace命名空间;指定为接口的全类名,就实现了动态绑定 -->
 7     <!-- select方法id和接口方法名一致,动态绑定
 8     public Employee getEmpById(Integer id); -->
 9     <select id="getEmpById" resultType="com.tzy.mybatis.Employee">
10         select id,last_name lastName,gender,email from tbl_employee where id = #{id}
11     </select>
12     <insert id="addEmp">
13         insert into tbl_employee(last_name,email,gender) values(#{lastName},#{email},#{gender})
14     </insert>
15     <update id="updateEmp">
16         update tbl_employee set last_name=#{lastName},email=#{email},gender=#{gender} where id=#{id}
17     </update>
18     <delete id="deleteEmpId" >
19         delete from tbl_employee where id = #{id}
20     </delete>
21 </mapper>
EmployeeMapper.xml
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 <!-- 1、mybatis可以使用properties来引入外部properties配置文件的内容:
 7         resource:引入类路径下的资源
 8         url:引入网络路径或者磁盘路径下
 9      -->
10      
11      
12      <properties resource="dbconfig.properties"></properties>
13     <environments default="development">
14         <environment id="development">
15             <transactionManager type="JDBC" />
16             <dataSource type="POOLED">
17                 <property name="driver" value="${jdbc.driver}" />
18                 <property name="url" value="${jdbc.url}" />
19                 <property name="username" value="${jdbc.username}" />
20                 <property name="password" value="${jdbc.password}" />
21             </dataSource>
22         </environment>
23     </environments>
24     
25     <!-- 将自己的SQL映射文件配置到全局里 -->
26     <mappers>
27         <mapper resource="EmployeeMapper.xml" />
28     </mappers>
29 </configuration>
mybatis-config.xml

 

insert获取自增主键方法:

技术分享图片

对于Oracle没有自增主键:获取其主键的方法:

技术分享图片

 

Mybatis配置

标签:实例   技术   tcl   技术分享   创建   jdbc   inpu   temp   tis   

原文地址:http://www.cnblogs.com/ttzzyy/p/7897068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!