MyBatis使用注解开发和无主配置文件开发的情况

MyBatis使用注解开发时就不在需要和接口对应的映射文件了

主要有以下几个注解

@Select() @Insert @Update() @Delete()

代码演示

项目结构:

MyBatis使用注解开发和无主配置文件开发的情况

数据库表设计

MyBatis使用注解开发和无主配置文件开发的情况

实体类

User

public class User implements Serializable {

 private long userId;
 private String userName;
 private Date birthday;
 private String sex;
 private String address;

getter setter toString

主配置文件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="mapUnderscoreToCamelCase" value="true"/>
 </settings>

 <!--起别名 typeAliases-->
 <typeAliases>
  <package name="com.codeyancy.cn.entity"/>
 </typeAliases>

 <environments default="development">
  <environment id="development">
   <transactionManager type="JDBC"/>
   <dataSource type="POOLED">
    <property name="driver" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
   </dataSource>
  </environment>
 </environments>

 <mappers>
  <!--包扫描-->
  <package name="com.codeyancy.cn.mapper"/>
 </mappers>
</configuration>

db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/web_test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=666

mapper接口

public interface UserMapper {

 /**
  * 查询所有用户信息
  */
 @Select("select * from user")
 List<User> findAll();

 /**
  * 根据id查询用户信息
  */
 @Select("select * from user where user_id=#{userId}")
 User findById(Integer id);

 /**
  * 新增
  */
 @Insert("insert into user (user_name,birthday,sex,address) values (#{userName},#{birthday},#{sex},#{address})")
 void insertUser(User user);

 /**
  * 修改
  */
 @Update("update user set user_name=#{userName},birthday=#{birthday},sex=#{sex},address=#{address} where user_id=#{userId}")
 void updateUser(User user);

 /**
  * 删除
  */
 @Delete("delete from user where user_id=#{userId}")
 void deleteUserById(Integer id);

	/**
  * 通过id或者名字模糊查询
  * 多个参数查询方式二:@Param
  */
 @Select("select * from user where user_id=#{id} or user_name like '%${name}%'")
 List<User> select(@Param("id") Integer id, @Param("name") String name);
}

测试类
Demo

public class Demo {

 public static void main(String[] args) {
  String path="mybatis-config.xml";
  InputStream resourceAsStream = null;
  try {
   resourceAsStream = Resources.getResourceAsStream(path);
  } catch (IOException e) {
   e.printStackTrace();
  }
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  SqlSession sqlSession = sqlSessionFactory.openSession(true);
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);

  //System.out.println(mapper.findAll());
  //System.out.println(mapper.findById(1));

  /*User user = new User();
  user.setUserName("老皮");
  user.setBirthday(new Date());
  mapper.insertUser(user);*/

  /*User user = new User();
  user.setUserName("李立林");
  user.setBirthday(new Date());
  user.setUserId(27);
  mapper.updateUser(user);*/

  //mapper.deleteUserById(27);

		System.out.println(mapper.select(1, "麻"));

  sqlSession.close();
  try {
   resourceAsStream.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

使用注解开发的一些问题

如果数据库字段名和实体类的属性名不一致,也不遵循驼峰命名。这种情况下,如果是使用映射文件可以用resultMap来解决。

但是注解开发也是可以解决的:

* 如果数据库列名和实体类属性名不一致或者没有开启驼峰命名,可以使用@Results解决这个问题
 *
 * @Select("sql语句")
 * @Results({
 *  @Result(column="",property=""),
 *  @Result(column="",property=""),
 *  @Result(column="",property=""),
 * })
 *
 * 使用注解也可以一对一,一对多
 *  @Result(column="",property="",one=@One("sql语句")), 一对一
 *  @Result(column="",property="",one=@Many("sql语句")), 一对多

在mybatis的使用中,主配置文件mybatis-config.xml 是十分重要的,那么能不能不使用主配置文件进行mybatis开发呢?

可以!!!

在官网中清楚的指出了可以使用java代码来代替xml主配置文件----》如下

MyBatis使用注解开发和无主配置文件开发的情况

尝试使用java类来代替主配置文件

MyBatisDemo

/**
 *使用java类代替mybatis-config.xml主配置文件
 */
public class MyBatisDemo {
 public static void main(String[] args) {
  //加载db.properties文件方式一
//  InputStream resourceAsStream = MyBatisDemo.class.getClassLoader().getResourceAsStream("db.properties");
//  Properties properties = new Properties();
//  try {
//   properties.load(resourceAsStream);
//  } catch (IOException e) {
//   e.printStackTrace();
//  }
//  String drive = properties.getProperty("jdbc.driverClassName");
//  String url = properties.getProperty("jdbc.url");
//  String name = properties.getProperty("jdbc.username");
//  String pass = properties.getProperty("jdbc.password");
//  DataSource dataSource = new PooledDataSource(drive,url,name,pass);

  //加载db.properties文件方式二(推荐)
  ResourceBundle bundle = ResourceBundle.getBundle("db");
  String drive = bundle.getString("jdbc.driverClassName");
  String url = bundle.getString("jdbc.url");
  String name = bundle.getString("jdbc.username");
  String pass = bundle.getString("jdbc.password");

  DataSource dataSource = new PooledDataSource(drive,url,name,pass);
  TransactionFactory transactionFactory = new JdbcTransactionFactory();
  Environment environment = new Environment("development", transactionFactory, dataSource);
  Configuration configuration = new Configuration(environment);
  //开启包扫描
  configuration.addMappers("com.codeyancy.cn.mapper");
  //开启驼峰命名
  configuration.setMapUnderscoreToCamelCase(true);
  //设置别名
  //configuration.getTypeAliasRegistry().registerAliases("com.codeyancy.cn.entity");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
  SqlSession sqlSession = sqlSessionFactory.openSession(true);
  UserMapper mapper = sqlSession.getMapper(UserMapper.class);

  //打印查询所有
  System.out.println(mapper.findAll());

  sqlSession.close();
 }
}

简单测试后,是可以使用的。