mybatis学习——使用注解开发
前言:
一个语句既可以通过 XML 定义,也可以通过注解定义。不过,由于 Java 注解的一些限制以及某些 MyBatis 映射的复杂性,要使用大多数高级映射(比如:嵌套联合映射),仍然需要使用 XML 配置。简单的说就是注解开发只适合一些简单的sql语句,如果sql语句太复杂,建议还是使用 XML 配置。
一、数据库
1.创建数据库,命名为mybatis
2.创建user表,sql语句如下:
create table user( id int primary key auto_increment, username varchar(32), password varchar(32) ); insert into user values(null,'张三','123456'); insert into user values(null,'李四','123456');
二、使用注解开发第一个程序
1.创建maven工程
项目结构:
2.导入依赖:在pom.xml文件中插入下边语句
<dependencies> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
3.编写核心配置文件:mybatis-config.xml,并引入外部配置文件:db.properties
*注意:
与使用xml映射的方式不同不同,使用注解开发的模式,我们不需要再编写映射文件,因此<mapper>直接映射到接口类
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> <properties resource="db.properties"/> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <package name="com.kuang.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper class="com.kuang.dao.UserMapper"/> </mappers> </configuration>
db.properties:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3307/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=root1234
4.编写工具类
package com.kuang.utils; 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 java.io.IOException; import java.io.InputStream; public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mabatis第一步:获取SqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //有了SqlsessionFactory,我们就可以从中获得SqlSession的实例了。 //SqlSession完全包含了面向数据库执行sql命令所需的所有方法 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
5.编写pojo类
package com.kuang.pojo;
import org.apache.ibatis.type.Alias;
@Alias("user")
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
6.编写接口类 (注解的使用就体现在这个类中)
package com.kuang.dao; import com.kuang.pojo.User; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; public interface UserMapper { @Select("select * from user") List<User> getUsers(); }
7.编写测试类
package com.kuang.dao; import com.kuang.pojo.User; import com.kuang.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.HashMap; import java.util.List; public class UserDaoTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(user); } sqlSession.close(); } }
三、使用注解实现CRUD语句
1.Retrieve(读取)
1.1 查询所有
public interface UserMapper { @Select("select * from user") List<User> getUsers(); }
1.2 根据id查询
public interface UserMapper {
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);
}
2.Create(增加)
public interface UserMapper {
@Insert("insert into user(id,name,pwd) value(#{id},#{name},#{pwd})")
int addUser(User user);
}
3.Update(更新)
public interface UserMapper {
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
}
4.Delete(删除)
public interface UserMapper { @Delete("delete from user where id = #{id}") int deleteUser(@Param("id") int id); }