myBatis系列之一:搭建开发环境

来源:互联网 发布:孙俪淘宝店铺名 编辑:程序博客网 时间:2024/05/21 22:53
1. pom.xml文件中加入mybatis和数据库依赖,这里使用mysql: 

Xml代码  收藏代码
  1. <properties>  
  2.   <mybatis.version>3.2.3</mybatis.version>  
  3.   <mysql.version>5.1.26</mysql.version>  
  4.   <slf4j.api.version>1.7.5</slf4j.api.version>  
  5.   <testng.version>6.8.7</testng.version>  
  6. </properties>  
  7.   
  8. <dependencies>  
  9.   <dependency>  
  10.     <groupId>org.mybatis</groupId>  
  11.     <artifactId>mybatis</artifactId>  
  12.     <version>${mybatis.version}</version>  
  13.   </dependency>  
  14.   <!-- Database driver -->  
  15.   <dependency>  
  16.     <groupId>mysql</groupId>  
  17.     <artifactId>mysql-connector-java</artifactId>  
  18.     <version>${mysql.version}</version>  
  19.   </dependency>  
  20.   <!-- mybatis启动要加载log4j -->  
  21.   <dependency>  
  22.     <groupId>org.slf4j</groupId>  
  23.     <artifactId>slf4j-log4j12</artifactId>  
  24.     <version>${slf4j.api.version}</version>  
  25.   </dependency>  
  26.   <!-- Test -->  
  27.   <dependency>  
  28.     <groupId>org.testng</groupId>  
  29.     <artifactId>testng</artifactId>  
  30.     <version>${testng.version}</version>  
  31.   </dependency>  
  32. </dependencies>  


2. 在类路径下创建mybatis的配置文件Configuration.xml 
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  3.   
  4. <configuration>  
  5.     <typeAliases><!-- 别名 -->  
  6.         <typeAlias alias="User" type="com.john.hbatis.model.User" />  
  7.     </typeAliases>  
  8.       
  9.     <environments default="development">  
  10.       <environment id="development">  
  11.         <transactionManager type="JDBC"/>  
  12.         <dataSource type="POOLED"><!-- 数据源 -->  
  13.             <property name="driver" value="com.mysql.jdbc.Driver" />  
  14.             <property name="url" value="jdbc:mysql://localhost:3306/hbatis" />  
  15.             <property name="username" value="root" />  
  16.             <property name="password" value="123456" />  
  17.         </dataSource>  
  18.       </environment>  
  19.     </environments>  
  20.       
  21.     <mappers><!-- ORM映射文件 -->  
  22.         <mapper resource="com/john/hbatis/model/User.xml" />  
  23.     </mappers>  
  24.  </configuration>  


3. 执行创建数据库和表的sql: 
Sql代码  收藏代码
  1. -- Create the database named 'hbatis'.  
  2. -- It's OK to use `, not OK to use ' or " surrounding the database name to prevent it from being interpreted as a keyword if possible.  
  3. CREATE DATABASE IF NOT EXISTS `hbatis`  
  4. DEFAULT CHARACTER SET = `UTF8`;  
  5.   
  6. -- Create a table named 'User'  
  7. CREATE TABLE `user` (  
  8.     `id` int(11) NOT NULL AUTO_INCREMENT,  
  9.     `namevarchar(50) DEFAULT NULL,  
  10.     `age` int(11) DEFAULT NULL,  
  11.     `address` varchar(200) DEFAULT NULL,  
  12.     PRIMARY KEY (`id`)  
  13. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  
  14.   
  15. -- Insert a test record  
  16. Insert INTO `userVALUES ('1''john''120''hangzhou,westlake');  


4. com.john.hbatis.model.User类: 
Java代码  收藏代码
  1. public class User {  
  2.     private int id;  
  3.     private String name;  
  4.     private String age;  
  5.     private String address;  
  6.     // Getters and setters are omitted  
  7.   
  8.     // 如果有带参数的构造器,编译器不会自动生成无参构造器。当查询需要返回对象时,ORM框架用反射来调用对象的无参构造函数,导致异常:java.lang.NoSuchMethodException: com.john.hbatis.model.User.<init>()  
  9.     // 这时需要明确写出:  
  10.     public User() {  
  11.     }  
  12.   
  13.     public User(String name, int age, String address) {  
  14.         this.name = name;  
  15.         this.age = age;  
  16.         this.address = address;  
  17.     }  
  18.   
  19. }  


com/john/hbatis/model路径下的User.xml 
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="com.john.hbatis.model.UserMapper">  
  4.     <select id="getUserById" parameterType="int" resultType="User">  
  5.         select * from `user` where id = #{id}  
  6.     </select>  
  7. </mapper>  


5. 测试类: 
Java代码  收藏代码
  1. public class MyBatisBasicTest {  
  2.     private static final Logger log = LoggerFactory.getLogger(MyBatisBasicTest.class);  
  3.     private static SqlSessionFactory sqlSessionFactory;  
  4.       
  5.     private static Reader reader;  
  6.       
  7.     @BeforeClass  
  8.     public static void initial() {  
  9.         try {  
  10.             reader = Resources.getResourceAsReader("Configuration.xml");  
  11.             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
  12.         } catch (IOException e) {  
  13.             log.error("Error thrown while reading the configuration: {}", e);  
  14.         } finally {  
  15.             if (reader != null) {  
  16.                 try {  
  17.                     reader.close();  
  18.                 } catch (IOException e) {  
  19.                     log.error("Error thrown while closing the reader: {}", e);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24.       
  25.     @Test  
  26.     public void queryTest() {  
  27.         SqlSession session = sqlSessionFactory.openSession();  
  28.         User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById"1);  
  29.         log.info("{}: {}", user.getName(), user.getAddress());  
  30.     }  
  31. }  
0 0
原创粉丝点击