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

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

主要有以下几个注解

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

代码演示

项目结构:
在这里插入图片描述
数据库表设计
在这里插入图片描述
实体类

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主配置文件----》如下
在这里插入图片描述
尝试使用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();
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值