sproingboot+mybatis自动创建数据库表

1.在现有的项目中的pom文件添加依赖

<dependency>
    <groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
    <artifactId>mybatis-enhance-actable</artifactId>
    <version>1.0.1</version>
</dependency>

2.创建配置文件属性(application.properties)

    当mybatis.table.auto=create时,系统启动后,会将所有的表删除掉,然后根据model中配置的结构重新建表,该操作会破坏原有数据。

mybatis.table.auto=update时,系统会自动判断哪些表是新建的,哪些字段要修改类型等,哪些字段要删除,哪些字段要新增,该操作不会破坏原有数据。

mybatis.table.auto=none时,系统不做任何处理。

mybatis.model.pack这个配置是用来配置要扫描的用于创建表的对象的包名

mybatis.table.auto=update
mybatis.model.pack=com.xuecheng.manage_course.entity
mybatis.database.type=mysql

3.创建配置文件类,并注入spring容器管理

   basePackages 的值不用改动

 @value里的值改成自己的对应的数据库链接信息(application.yml、application.properties)

 setTypeAliasesPackage的值 改成自己创建表的对象的包名



import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * @author : LMY
 * @Date: 2020/5/1
 */
@Configuration
@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"})
public class TestConfig {

    @Value("${spring.datasource.druid.driverClassName}")
    private String driver;

    @Value("${spring.datasource.druid.url}")
    private String url;

    @Value("${spring.datasource.druid.username}")
    private String username;

    @Value("${spring.datasource.druid.password}")
    private String password;

    @Bean
    public PropertiesFactoryBean configProperties() throws Exception{
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        propertiesFactoryBean.setLocations(resolver.getResources("classpath*:application.properties"));
        return propertiesFactoryBean;
    }

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(30);
        dataSource.setInitialSize(10);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(true);
        return dataSource;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource());
        return dataSourceTransactionManager;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.xuecheng.manage_course.entity.*");
        return sqlSessionFactoryBean;
    }

}

4.创建实体类

package com.xuecheng.manage_course.entity;




import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;
import com.gitee.sunchenbin.mybatis.actable.command.BaseModel;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;


import java.util.Date;

/**
 * @author : LMY
 * @Date: 2020/5/1
 */
@Table(name = "test")
public class Test extends BaseModel {

    private static final long serialVersionUID = 5199200306752426433L;

    @Column(name = "id",type = MySqlTypeConstant.INT,length = 11,isKey = true,isAutoIncrement = true)
    private Integer id;

    @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 111)
    private String  name;

    @Column(name = "description",type = MySqlTypeConstant.TEXT)
    private String  description;

    @Column(name = "create_time",type = MySqlTypeConstant.DATETIME)
    private Date create_time;

    @Column(name = "update_time",type = MySqlTypeConstant.DATETIME)
    private Date    update_time;

    @Column(name = "number",type = MySqlTypeConstant.BIGINT,length = 5)
    private Long    number;

    @Column(name = "lifecycle",type = MySqlTypeConstant.CHAR,length = 1)
    private String  lifecycle;

    @Column(name = "dekes",type = MySqlTypeConstant.DOUBLE,length = 5,decimalLength = 2)
    private Double  dekes;

    //省略Setter、Getter

}

5.启动项目即可

详细请查看 https://blog.csdn.net/bin470398393/article/details/90633557

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 是一个基于 Spring 框架的快速开发框架,而 MyBatis Plus 是 MyBatis 的增强工具,为 MyBatis 提供了更加便捷的操作数据库的方式。 在 Spring Boot 中使用 MyBatis Plus 操作数据库,需要进行以下步骤: 1. 引入 MyBatis Plus 的依赖 在 pom.xml 文件中引入 MyBatis Plus 的依赖,如下所示: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> ``` 2. 配置数据源 在 application.properties 或 application.yml 中配置数据库的相关信息,如下所示: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 3. 创建实体类 创建需要操作的实体类,并使用 MyBatis Plus 的注解 @TableName 指定名,如下所示: ``` @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; } ``` 4. 创建 Mapper 接口 创建 Mapper 接口,并继承 MyBatis Plus 的 BaseMapper 接口,如下所示: ``` public interface UserMapper extends BaseMapper<User> { } ``` 5. 使用 MyBatis Plus 进行操作数据库 在 Service 层中注入 Mapper 接口,并使用 MyBatis Plus 提供的方法进行操作数据库,如下所示: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectById(id); } @Override public List<User> getAllUsers() { return userMapper.selectList(null); } @Override public void saveUser(User user) { userMapper.insert(user); } @Override public void updateUser(User user) { userMapper.updateById(user); } @Override public void deleteUser(Long id) { userMapper.deleteById(id); } } ``` 以上就是 Spring Boot 中使用 MyBatis Plus 操作数据库的基本步骤。在使用 MyBatis Plus 进行操作数据库时,可以使用它提供的丰富的 API,如 LambdaWrapper、QueryWrapper 等,更加便捷地进行数据库的操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值