iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >MyBatis使用注解开发和无主配置文件开发的情况
  • 408
分享到

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

2024-04-02 19:04:59 408人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

mybatis使用注解开发时就不在需要和接口对应的映射文件了 主要有以下几个注解 @Select() @Insert @Update() @Delete() 代码演示 项目

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();

 
 @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);

	
 @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));

  

  

  //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



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();
 }
}

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

到此这篇关于MyBatis使用注解开发和无主配置文件开发的情况的文章就介绍到这了,更多相关MyBatis注解开发无主配置文件内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

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

本文链接: https://www.lsjlt.com/news/121679.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作