MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。项目GitHub地址
下载MyBatis源码,导入到IDEA工程(Maven工程)中,工程结构如下:
在pom.xml中新增如下依赖:
<dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.38version> dependency> <dependency> <groupId>commons-logginggroupId> <artifactId>commons-loggingartifactId> <version>1.2version> dependency> <dependency> <groupId>org.apache.logging.log4jgroupId> <artifactId>log4j-apiartifactId> <version>2.6.2version> dependency> <dependency> <groupId>ognlgroupId> <artifactId>ognlartifactId> <version>3.1.6version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>1.7.21version> dependency> <dependency> <groupId>cglibgroupId> <artifactId>cglibartifactId> <version>2.2.2version> dependency>
等待依赖更新完毕后,如果出现了@Override覆盖接口方法报错问题,请参考IDEA中 @override报错的解决方法。
MyBatis配置conf.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> <settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="false"/> settings> <typeAliases> <typeAlias type="com.luoxn28.dao.User" alias="User"/> typeAliases> <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://192.168.1.150:3306/xxx" /> <property name="username" value="xxx" /> <property name="password" value="xxx" /> dataSource> environment> environments> <mappers> <mapper resource="userMapper.xml"/> mappers> configuration>
User类的映射文件userMapper.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="com.luoxn28.dao.UserDao"> <select id="getById" parameterType="int" resultType="User"> SELECT * FROM user WHERE id=#{id}; select> <select id="getAll" resultType="com.luoxn28.dao.User"> SELECT * FROM user; select> mapper>
测试代码:
/** * MyBatis测试类 */ public class TestMain { public static void main(String[] args) throws IOException { String resouce = "conf.xml"; //InputStream is = TestMain.class.getClassLoader().getResourceAsStream(resouce); InputStream is = Resources.getResourceAsStream(resouce); // 构建sqlSession工厂 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sqlSessionFactory.openSession(); /** * 第一种方式: 直接执行已映射的 SQL 语句 */ String statement = "com.luoxn28.dao.UserDao.getById"; User user = session.selectOne(statement, 1); System.out.println(user); System.out.println("---------------------"); /** * 第二种方式: 执行更清晰和类型安全的代码 */ UserDao userDao = session.getMapper(UserDao.class); user = userDao.getById(1); System.out.println(user); } }
User用户类:
/** * User - 用户类 */ public class User { public static final int MAN = 0; // 男生 public static final int WOMAN = 1; // 女生 public static final int OTHER = 2; // 其他 private int id; // 用户id private String name; // 用户名 private String password; // 用户密码 private int sex; // 用户性别 private String email; // 用户邮箱 private String phone; // 用户手机 private String admin; // 用户是否是管理员,"admin"表示是管理员,其他为普通用户 public User() { } public User(String name, String password, int sex, String email, String phone) { this.name = name; this.password = password; this.sex = sex; this.email = email; this.phone = phone; this.admin = ""; } public User(String name, String password, String sex, String email, String phone) { this.name = name; this.password = password; setSex(sex); // this.sex = sex; this.email = email; this.phone = phone; this.admin = ""; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public void setSex(String sexStr) { int sex = Integer.valueOf(sexStr); switch (Integer.valueOf(sexStr)) { case 0: { this.sex = MAN; break; } case 1: { this.sex = WOMAN; break; } default: { this.sex = OTHER; break; } } } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAdmin() { return admin; } public void setAdmin(String admin) { this.admin = admin; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", sex=" + sex + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", admin='" + admin + '\'' + '}'; } }
UserDao用户操作类
/** * UserDao - User操作类 */ public interface UserDao { public User getById(int id); public ListgetAll(); }
以上示例代码是用XML来设置映射语句的,当然,也可以用Java注解来做。比如,上面的 XML 示例可被替换如下:
/** * UserDao - User操作类 */ public interface UserDao { @Select("SELECT * FROM user WHERE id=#{id}") public User getById(int id); @Select("SELECT * FROM user") public ListgetAll(); }
使用注解时调用实例:
UserDao userDao = session.getMapper(UserDao.class); user = userDao.getById(1); System.out.println(user);
对于简单语句来说,注解使代码显得更加简洁,然而 Java 注解对于稍微复杂的语句就会力不从心并且会显得更加混乱。因此,如果你需要做很复杂的事情,那么最好使用 XML 来映射语句。选择何种方式以及映射语句的定义的一致性对你来说有多重要这些完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和 XML 的语句映射方式间自由移植和切换。注意:UserDao接口的getById方法配置了注解,那么就不要XML中配置了,否则程序会报异常。
参考:
1、IDEA中 @override报错的解决方法
2、MyBatis3中文文档