idea 创建springboot mybatis过程 IDEA创建springboot + mybatis项目全过程(步骤详解)
stephenChen946 人气:0鉴于隔很久再在IDEA新建springboot项目时,会出现对步骤不确定的情况,因此,写下这篇博客记录创建一个可运行的springboot+mybatis项目的全过程。
步骤如下:
1.打开IDEA
2.File ==> new ==> project ,如图:
3.选择spring Initializr ==> 右边的Project SDK我选的是我已经安装的1.8版本,其他默认 ==> 点击next
4.填写Group (自己随意就行,我的是cn + 个人英文名 + study) ==> 填写 Artifact (也是自己随意就行,这个也是你的项目名) ==> 点击next ,如图:
5.选择项目所需依赖(由于项目是springboot+mybatis的Java后台项目,因此需要勾上三个依赖) ==> 点击next ,如图:
6.选择项目路径 ==> 点击finish ,如图:
6.最终生成的项目代码目录如图(resources目录下的static和templates目录无用,可以删掉):
(注:如果DemoprojectApplication类(即启动类)的图标显示是 J 而不是 C ,则说名该项目还没有被初始化为maven项目,
只需要在项目的pom.xml文件上右键,再选择 Add as maven 即可)
至此,springboot项目搭建完成一半,还需要做mybatis的配置,如下:
7.数据库和mybatis的配置
7.1 在application.properties填入数据库连接参数和mybatis配置信息,application.properties内容如下:
#1.项目启动的端口 server.port=18902 #2.数据库连接参数 #2.1jdbc驱动,示数据库厂商决定,这是mysql的驱动 jdbc.driver=com.mysql.cj.jdbc.Driver #2.2数据库连接url,包括ip(127.0.0.1)、端口(3306)、数据库名(testdb) jdbc.url=jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false #2.3数据库账号名 jdbc.username=root #2.4数据库密码 jdbc.password=mypassword #3.Mybatis配置 #3.1 mybatis配置文件所在路径 mybatis_config_file=mybatis-config.xml #3.2 mapper文件所在路径,这样写可匹配mapper目录下的所有mapper,包括其子目录下的 mapper_path=/mapper/**/**.xml #3.3 entity所在包 entity_package=cn.stephen.study.demoproject.entity
示例如图:
7.2 在resources目录下新建 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> <!--配置全局属性--> <settings> <!--使用jdbc的getGeneratedKeys获取数据库自增主键值--> <setting name="useGeneratedKeys" value="true"/> <!--使用列标签替换列别名 默认未true--> <setting name="useColumnLabel" value="true" /> <!--开启驼峰式命名转换:Table{create_time} -> Entity{createTime}--> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> </configuration>
效果如图:
7.3 新建 config包,在其中新建配置类。共三个配置类,如图:
DataSourceConfiguration类的代码如下:
package cn.stephen.study.demoproject.config.dao; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.beans.PropertyVetoException; /** * 数据库配置类 */ @Configuration public class DataSourceConfiguration { @Value("${jdbc.driver}") private String jdbcDriver; @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String jdbcUsername; @Value("${jdbc.password}") private String jdbcPassword; @Bean(name = "dataSouce") public ComboPooledDataSource createDataSouce() throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(jdbcDriver); dataSource.setJdbcUrl(jdbcUrl); dataSource.setUser(jdbcUsername); dataSource.setPassword(jdbcPassword); //关闭连接后不自动commit dataSource.setAutoCommitOnClose(false); return dataSource; } }
SessionFactoryConfiguration类的代码如下:
package cn.stephen.study.demoproject.config.dao; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; import java.io.IOException; /** * 数据库sqlSession配置类 */ @Configuration public class SessionFactoryConfiguration { @Value("${mapper_path}") private String mapperPath; @Value("${mybatis_config_file}") private String mybatisConfigFilePath; @Autowired private DataSource dataSouce; @Value("${entity_package}") private String entityPackage; @Bean(name="sqlSessionFactory") public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath)); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath; sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath)); sqlSessionFactoryBean.setDataSource(dataSouce); sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage); return sqlSessionFactoryBean; } }
TransactionManagementConfiguration类的代码如下:
package cn.stephen.study.demoproject.config.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import javax.sql.DataSource; /** * 事务配置类,不可缺少,尚未知具体作用 */ @Configuration @EnableTransactionManagement public class TransactionManagementConfiguration implements TransactionManagementConfigurer{ @Autowired private DataSource dataSource; @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } }
三个类的代码写完后,在DataSourceConfiguration类中会报找不到某些类的错,在下一步解决。
7.4 在 pom.xml文件的<dependencies></dependencies>插入以下两个依赖
<!--线程池--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
至此,项目配置已完成。。。。
8. 接下来,就按最普遍的分层代码目录结构来写一个基本的测试来测试项目是否能正常运行。代码目录结果如图:
一共需要新建4个包(controller、service、dao、entity)和一个目录(mapper);
8.1 controller包放控制层代码,TestController类的代码如下:
package cn.stephen.study.demoproject.controller; import cn.stephen.study.demoproject.entity.TestEntity; import cn.stephen.study.demoproject.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/demoproject/test") public class TestController { @Autowired private TestService testService ; @RequestMapping(value = "/get/{id}",method = RequestMethod.GET) public TestEntity test(@PathVariable Integer id){ System.out.println("id:" + id); return testService.getById(id); } }
8.2 service层放业务处理层代码,TestService类的代码如下:
package cn.stephen.study.demoproject.service; import cn.stephen.study.demoproject.dao.TestDao; import cn.stephen.study.demoproject.entity.TestEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TestService { @Autowired private TestDao testDao ; public TestEntity getById(Integer id){ return testDao.getById(id); } }
8.3 dao包放数据存取层代码,TestDao代码如下:
package cn.stephen.study.demoproject.dao; import cn.stephen.study.demoproject.entity.TestEntity; import org.apache.ibatis.annotations.Mapper; @Mapper public interface TestDao { TestEntity getById(Integer id); }
8.4 entity包放数据库表对应的实体类,TestEntity实体类代码如下:
package cn.stephen.study.demoproject.entity; public class TestEntity { protected Integer id ; protected String magicId ; protected String firstName ; protected String lastName ; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMagicId() { return magicId; } public void setMagicId(String magicId) { this.magicId = magicId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
对应的数据库表的sql语句如下:
CREATE TABLE `test` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `magic_id` varchar(32) NOT NULL, `first_name` varchar(32) NOT NULL, `last_name` varchar(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
8.5 mapper目录放dao层代码的具体实现(这是mybatis的特色,用xml文件来实现数据存取),TestDaoMapper的内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="cn.stephen.study.demoproject.dao.TestDao"> <!-- 根据主键查询--> <select id="getById" resultType="cn.stephen.study.demoproject.entity.TestEntity" parameterType="java.lang.Integer" > select * from test where id = #{id} </select> </mapper>
测试代码写完,就可以打开postman去做测试了。
(注:搜索 postman下载 即可在官网上下载postman软件)
测试结果如图:
9.结束语:
至此,搭建springboot + mybatis 的Java后台项目已经结束。。
附上该项目示例的github地址:https://github.com/StephenChen1/demoproject.git
加载全部内容