springboot mybaties mysql ElasticSearch

1.idea创建springboot项目

1.创建项目

2.下一步

3.下一步

4.这样项目便创建完成

2.集成mybaties和mysql

1.pom文件依赖

<!--mybatis 配置-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${org.mybatis.spring.boot.version}</version>
</dependency>
<!--数据库配置-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${com.alibaba.version}</version>
</dependency>

<!--添加上插件,使得用generator配置文件去逆向生成mapper,model和dao-->

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
       <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <configuration>
                <verbose>true</verbose>
                <overwrite>true</overwrite>
            </configuration>
       </plugin>
    </plugins>
</build>

2.GeneratorConfig.xml配置文件设置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

   <context id="mysql" targetRuntime="MyBatis3">
      <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>
      <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
      <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>
      <commentGenerator>
         <!-- 避免生成注解 <propertyname="suppressDate" value="true" /> -->
         <property name="suppressAllComments" value="true" />
      </commentGenerator>
      <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}"
                  userId="${spring.datasource.username}" password="${spring.datasource.password}" />
      <!-- 指定生成的类型为java类型,避免数据库中number等类型字段 -->
      <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
         <!--
                true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型
                false:默认,
                    scale>0;length>18:使用BigDecimal;
                    scale=0;length[10,18]:使用Long;
                    scale=0;length[5,9]:使用Integer;
                    scale=0;length<5:使用Short;
             -->
         <property name="forceBigDecimals" value="false"/>
      </javaTypeResolver>

      <!-- 生成model模型,对应的包,存放位置可以指定具体的路径,如/ProjectName/src,也可以使用MAVEN来自动生成 -->
      <javaModelGenerator targetPackage="com.learn.message.model"
                     targetProject="src/main/java">
         <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
         <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
         <property name="enableSubPackages" value="false" />
         <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
         <property name="trimStrings" value="true" />
      </javaModelGenerator>

      <!--对应的xml mapper文件 -->
      <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources/mybatis">
         <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
         <property name="enableSubPackages" value="false" />
      </sqlMapGenerator>

      <!-- 对应的dao接口 -->
      <javaClientGenerator type="XMLMAPPER"
                      targetPackage="com.learn.message.dao"
                      targetProject="src/main/java">
         <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
         <property name="enableSubPackages" value="false" />
         <property name="useActualColumnNames" value="true" />
      </javaClientGenerator>
        <table tableName="userinfo" domainObjectName="UserInfoPO"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false" >
            <property name="useActualColumnNames" value="false"/>
        </table>
    </context>
</generatorConfiguration>

3.配置文件的配置application.properties

#数据库的配置
spring.datasource.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#Mybatis 配置
#包路径扫描
mybatis.type-aliases-package=com.learn.message.model
#主数据源用到的mappers文件
mybatis.mapper-location=classpath:mybatis/mappers/*.xml
#分页方言
pageHelper.dialect=oracle

4.数据源的配置

 /*
 * @ClassName: DruidDataSourceConfig
 * @Description: 数据源的配置
 * @author ss
 * @date 2019年07月05日 下午2:50:12
 */

@Configuration
@MapperScan(basePackages = "com.learn.message.dao", sqlSessionFactoryRef = "sqlSessionFactory")
public class DruidDataSourceConfig {
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    @Value("${mybatis.mapper-location}")
    private String mapperLocations;

    @Value("${mybatis.config-location}")
    private String configLocations;

    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;

    @Value("${pageHelper.dialect}")
    private String pageHelperDialect;


    //数据源
    @Bean(name = "dataSource", destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.url")
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        //设置mapper.xml文件所在位置
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
        //设置mybatis-config.xml配置文件所在位置
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource(configLocations));
        //添加分页插件、打印sql插件
        Interceptor[] plugins = new Interceptor[] {sqlInterceptor(),pageHelper()};
        sqlSessionFactoryBean.setPlugins(plugins);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "transactionalManager")
    @Primary
    public PlatformTransactionManager transactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean(name = "pageHelper")
    @Primary
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        p.setProperty("returnPageInfo", "check");
        p.setProperty("params", "count=countSql");
        p.setProperty("dialect", pageHelperDialect);
        pageHelper.setProperties(p);
        return pageHelper;
    }
}

5.事物配置

在启动类上添加EnableTransactionManagement注解

注意

启动的时候可能会报java.lang.UnsupportedClassVersionError: org/springframework/boot/SpringApplication : Unsupported major.minor version 52.0错,这个时候,是因为我用的1.7的jdk,但是springboot创建的时候是1.8。将pom文件依赖包的版本号改为低的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值