MyBatis 是支持普通 SQL 查詢,存儲過程和高級映射的優秀持久層框架。MyBatis 消除了幾乎全部的 JDBC 代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML 或註解用於配置和原始映射,將接口和 Java 的 POJOs(Plan Old Java Objects,普通的 Java 對象)映射成數據庫中的記錄。java
不管是用過的 hibernate,Mybatis,你均可以法相他們有一個共同點:web
建立用戶表:spring
Create TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(50) DEFAULT NULL, `userAge` int(11) DEFAULT NULL, `userAddress` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; Insert INTO `user` VALUES ('1', 'summer', '100', 'shanghai,pudong');
結構圖以下:sql
Configuration.xml: 這裏使用mariadb做爲開發環境數據庫
<?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> <typeAliases> <typeAlias alias="User" type="demo.mybatis.helloworld.model.User"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.mariadb.jdbc.Driver"/> <property name="url" value="jdbc:mariadb://192.168.1.202:3306/demo" /> <property name="username" value="root"/> <property name="password" value="111111"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/User.xml"/> </mappers> </configuration>
pom.xml:apache
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>demo</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client --> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>1.4.6</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
User.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="demo.mybatis.helloworld.mapper.UserMapper"> <select id="selectUserByID" parameterType="int" resultType="User"> select * from `user` where id = #{id} </select> </mapper>
User.java:
session
public class User { private int id; private String userName; private Integer userAge; private String userAddress; //get and set... }
UserMapper:mybatis
public interface UserMapper { User selectUserByID(int id); }
Test.java:app
import java.io.Reader; import demo.mybatis.helloworld.mapper.UserMapper; import demo.mybatis.helloworld.model.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * Created by carl.yu on 2016/12/8. */ public class Test { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("Configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } public static SqlSessionFactory getSession() { return sqlSessionFactory; } public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userOperation=session.getMapper(UserMapper.class); User user = userOperation.selectUserByID(1); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); } finally { session.close(); } } }
這裏直接用接口的方式編程。這種方式,要注意的一個地方就是。在 User.xml 的配置文件中,mapper namespace="demo.mybatis.helloworld.mapper.UserMapper"
,命名空間很是重要,不能有錯,必須與咱們定義的 package 和 接口一致。若是不一致就會出錯,這一章主要在上一講基於接口編程的基礎上完成以下事情:
查詢出列表,也就是返回 list, 在咱們這個例子中也就是 List , 這種方式返回數據,須要在 User.xml 裏面配置返回的類型 resultMap, 注意不是 resultType, 而這個 resultMap 所對應的應該是咱們本身配置的
<!-- 爲了返回list 類型而定義的returnMap --> <resultMap type="User" id="resultListUser"> <id column="id" property="id" /> <result column="userName" property="userName" /> <result column="userAge" property="userAge" /> <result column="userAddress" property="userAddress" /> </resultMap>
查詢列表的語句在 User.xml 中
<!-- 返回list 的select 語句,注意 resultMap 的值是指向前面定義好的 --> <select id="selectUsers" parameterType="string" resultMap="resultListUser"> select * from user where userName like #{userName} </select>
在 UserMapper接口中增長方法:public List selectUsers(String userName);
如今在 Test 類中作測試
public void getUserList(String userName){ SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userOperation=session.getMapper(UserMapper.class); List<User> users = userOperation.selectUsers(userName); for(User user:users){ System.out.println(user.getId()+":"+user.getUserName()+":"+user.getUserAddress()); } } finally { session.close(); } }
如今在 main 方法中能夠測試:
public static void main(String[] args) { Test testUser=new Test(); testUser.getUserList("%"); }
能夠看到,結果成功查詢出來。若是是查詢單個數據的話,用第二講用過的方法就能夠了。
在 UseMapper接口中增長方法:
public void addUser(User user);
在 User.xml 中配置
<!--執行增長操做的SQL語句。id和parameterType 分別與UserMapper接口中的addUser方法的名字和 參數類型一致。以#{name}的形式引用Student參數 的name屬性,MyBatis將使用反射讀取Student參數 的此屬性。#{name}中name大小寫敏感。引用其餘 的gender等屬性與此一致。seGeneratedKeys設置 爲"true"代表要MyBatis獲取由數據庫自動生成的主 鍵;keyProperty="id"指定把獲取到的主鍵值注入 到Student的id屬性--> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress}) </insert>
而後在 Test 中寫測試方法:
/** * 測試增長,增長後,必須提交事務,不然不會寫入到數據庫. */ public void addUser(){ User user=new User(); user.setUserAddress("人民廣場"); user.setUserName("飛鳥"); user.setUserAge(80); SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userOperation=session.getMapper(UserMapper.class); userOperation.addUser(user); session.commit(); System.out.println("當前增長的用戶 id爲:"+user.getId()); } finally { session.close(); } }
方法相似,先在 UserMapper中增長方法:
public void updateUser(User user);
而後配置 User.xml
<update id="updateUser" parameterType="User" > update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id} </update>
Test 類總的測試方法以下:
public void updateUser(){ //先獲得用戶,而後修改,提交。 SqlSession session = sqlSessionFactory.openSession(); try { UserMapper userOperation=session.getMapper(UserMapper.class); User user = userOperation.selectUserByID(4); user.setUserAddress("原來是魔都的浦東創新園區"); userOperation.updateUser(user); session.commit(); } finally { session.close(); } }
同理,UserMapper增長方法:public void deleteUser(int id);
配置 User.xml
<delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete>
而後在 Test 類中寫測試方法:
/** * 刪除數據,刪除必定要 commit. * @param id */ public void deleteUser(int id){ SqlSession session = sqlSessionFactory.openSession(); try { IUserOperation userOperation=session.getMapper(IUserOperation.class); userOperation.deleteUser(id); session.commit(); } finally { session.close(); } }
這樣,全部增刪改查都完成了,注意在增長,更改,刪除的時候要調用 session.commit(),這樣纔會真正對數據庫進行操做,不然是沒有提交的。
到此爲止,簡單的單表操做,應該都會了,接下來的時間了,我會講多表聯合查詢,以及結果集的選取。
參考文章:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
MyBatis-Spring-Boot-Starter will:
能夠配置的信息有:
Property | Description |
---|---|
config-location | MyBatis xml config file (optional) |
mapper-locations | Mapper xml config files (optional) |
type-aliases-package | Package to search for type aliases (optional) |
type-handlers-package | Package to search for type aliases (optional) |
executor-type | Executor type: SIMPLE, REUSE, BATCH (optional) |
文件圖:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>demo</groupId> <artifactId>demo.mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>mybatis spring boot demo</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client --> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>1.4.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
application.properties:
jdbc.driverClassName=org.mariadb.jdbc.Driver jdbc.url=jdbc:mariadb://192.168.1.202:3306/demo jdbc.username=root jdbc.password=111111 mybatis.config-location=classpath:mybatis-config.xml logging.level.root=WARN logging.level.sample.mybatis.mapper=TRACE
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> <typeAliases> <!--<package name="sample.mybatis.domain"/>--> <typeAlias alias="User" type="demo.domain.User"/> </typeAliases> <mappers> <mapper resource="mapper/User.xml"/> </mappers> </configuration>
MyBatisConfig: 配置數據源
package demo; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import javax.sql.DataSource; import java.util.Properties; /** * Created by carl.yu on 2016/12/8. */ @Configuration public class MyBatisConfig { @Autowired private Environment env; /** * 建立數據源 * * @Primary 該註解表示在同一個接口有多個實現類能夠注入的時候,默認選擇哪個,而不是讓@autowire註解報錯 */ @Bean //@Primary public DataSource getDataSource() throws Exception { Properties props = new Properties(); props.put("driverClassName", env.getProperty("jdbc.driverClassName")); props.put("url", env.getProperty("jdbc.url")); props.put("username", env.getProperty("jdbc.username")); props.put("password", env.getProperty("jdbc.password")); props.put("testWhileIdle", "false"); return DruidDataSourceFactory.createDataSource(props); } }
配置User.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="demo.dao.UserMapper"> <select id="selectUserByID" parameterType="int" resultType="User"> select * from `user` where id = #{id} </select> <resultMap type="User" id="resultListUser"> <id column="id" property="id"/> <result column="userName" property="userName"/> <result column="userAge" property="userAge"/> <result column="userAddress" property="userAddress"/> </resultMap> <!-- 返回list 的select 語句,注意 resultMap 的值是指向前面定義好的 --> <select id="selectUsers" parameterType="string" resultMap="resultListUser"> select * from user where userName like #{userName} </select> <!--執行增長操做的SQL語句。id和parameterType 分別與UserMapper接口中的addUser方法的名字和 參數類型一致。以#{name}的形式引用Student參數 的name屬性,MyBatis將使用反射讀取Student參數 的此屬性。#{name}中name大小寫敏感。引用其餘 的gender等屬性與此一致。seGeneratedKeys設置 爲"true"代表要MyBatis獲取由數據庫自動生成的主 鍵;keyProperty="id"指定把獲取到的主鍵值注入 到Student的id屬性--> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress}) </insert> <update id="updateUser" parameterType="User"> update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> </mapper>
配置UserMapper:
package demo.dao; import demo.domain.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * Created by carl.yu on 2016/12/8. */ @Mapper public interface UserMapper { User selectUserByID(int id); public List selectUsers(String userName); public void addUser(User user); public void updateUser(User user); }
能夠直接使用了: UserService
package demo.service; import demo.dao.UserMapper; import demo.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by carl.yu on 2016/12/8. */ @Service public class UserService { @Autowired private UserMapper userMapper; @Transactional(readOnly = true) public List<User> findAll() { return userMapper.selectUsers("%"); } }