IDEA創(chuàng)建springboot + mybatis項(xiàng)目全過(guò)程(步驟詳解)
鑒于隔很久再在IDEA新建springboot項(xiàng)目時(shí),會(huì)出現(xiàn)對(duì)步驟不確定的情況,因此,寫下這篇博客記錄創(chuàng)建一個(gè)可運(yùn)行的springboot+mybatis項(xiàng)目的全過(guò)程。
步驟如下:
1.打開IDEA
2.File ==> new ==> project ,如圖:
3.選擇spring Initializr ==> 右邊的Project SDK我選的是我已經(jīng)安裝的1.8版本,其他默認(rèn) ==> 點(diǎn)擊next
4.填寫Group (自己隨意就行,我的是cn + 個(gè)人英文名 + study) ==> 填寫 Artifact (也是自己隨意就行,這個(gè)也是你的項(xiàng)目名) ==> 點(diǎn)擊next ,如圖:
5.選擇項(xiàng)目所需依賴(由于項(xiàng)目是springboot+mybatis的Java后臺(tái)項(xiàng)目,因此需要勾上三個(gè)依賴) ==> 點(diǎn)擊next ,如圖:
6.選擇項(xiàng)目路徑 ==> 點(diǎn)擊finish ,如圖:
6.最終生成的項(xiàng)目代碼目錄如圖(resources目錄下的static和templates目錄無(wú)用,可以刪掉):
(注:如果DemoprojectApplication類(即啟動(dòng)類)的圖標(biāo)顯示是 J 而不是 C ,則說(shuō)名該項(xiàng)目還沒(méi)有被初始化為maven項(xiàng)目,
只需要在項(xiàng)目的pom.xml文件上右鍵,再選擇 Add as maven 即可)
至此,springboot項(xiàng)目搭建完成一半,還需要做mybatis的配置,如下:
7.數(shù)據(jù)庫(kù)和mybatis的配置
7.1 在application.properties填入數(shù)據(jù)庫(kù)連接參數(shù)和mybatis配置信息,application.properties內(nèi)容如下:
#1.項(xiàng)目啟動(dòng)的端口server.port=18902 #2.數(shù)據(jù)庫(kù)連接參數(shù)#2.1jdbc驅(qū)動(dòng),示數(shù)據(jù)庫(kù)廠商決定,這是mysql的驅(qū)動(dòng)jdbc.driver=com.mysql.cj.jdbc.Driver#2.2數(shù)據(jù)庫(kù)連接url,包括ip(127.0.0.1)、端口(3306)、數(shù)據(jù)庫(kù)名(testdb)jdbc.url=jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false#2.3數(shù)據(jù)庫(kù)賬號(hào)名jdbc.username=root#2.4數(shù)據(jù)庫(kù)密碼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文件,文件內(nèi)容如下:
<?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獲取數(shù)據(jù)庫(kù)自增主鍵值--> <setting name='useGeneratedKeys' value='true'/> <!--使用列標(biāo)簽替換列別名 默認(rèn)未true--> <setting name='useColumnLabel' value='true' /> <!--開啟駝峰式命名轉(zhuǎn)換:Table{create_time} -> Entity{createTime}--> <setting name='mapUnderscoreToCamelCase' value='true' /> </settings></configuration>
效果如圖:
7.3 新建 config包,在其中新建配置類。共三個(gè)配置類,如圖:
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; /** * 數(shù)據(jù)庫(kù)配置類 */@Configurationpublic 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); //關(guān)閉連接后不自動(dòng)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; /** * 數(shù)據(jù)庫(kù)sqlSession配置類 */ @Configurationpublic 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; /** * 事務(wù)配置類,不可缺少,尚未知具體作用 */@Configuration@EnableTransactionManagementpublic class TransactionManagementConfiguration implements TransactionManagementConfigurer{ @Autowired private DataSource dataSource; @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); }}
三個(gè)類的代碼寫完后,在DataSourceConfiguration類中會(huì)報(bào)找不到某些類的錯(cuò),在下一步解決。
7.4 在 pom.xml文件的<dependencies></dependencies>插入以下兩個(gè)依賴
<!--線程池--><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>
至此,項(xiàng)目配置已完成。。。。
8. 接下來(lái),就按最普遍的分層代碼目錄結(jié)構(gòu)來(lái)寫一個(gè)基本的測(cè)試來(lái)測(cè)試項(xiàng)目是否能正常運(yùn)行。代碼目錄結(jié)果如圖:
一共需要新建4個(gè)包(controller、service、dao、entity)和一個(gè)目錄(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層放業(yè)務(wù)處理層代碼,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; @Servicepublic class TestService { @Autowired private TestDao testDao ; public TestEntity getById(Integer id){ return testDao.getById(id); }}
8.3 dao包放數(shù)據(jù)存取層代碼,TestDao代碼如下:
package cn.stephen.study.demoproject.dao; import cn.stephen.study.demoproject.entity.TestEntity;import org.apache.ibatis.annotations.Mapper; @Mapperpublic interface TestDao { TestEntity getById(Integer id); }
8.4 entity包放數(shù)據(jù)庫(kù)表對(duì)應(yīng)的實(shí)體類,TestEntity實(shí)體類代碼如下:
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; }}
對(duì)應(yīng)的數(shù)據(jù)庫(kù)表的sql語(yǔ)句如下:
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層代碼的具體實(shí)現(xiàn)(這是mybatis的特色,用xml文件來(lái)實(shí)現(xiàn)數(shù)據(jù)存?。琓estDaoMapper的內(nèi)容如下:
<?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'> <!-- 根據(jù)主鍵查詢--> <select resultType='cn.stephen.study.demoproject.entity.TestEntity' parameterType='java.lang.Integer' > select * from test where id = #{id} </select></mapper>
測(cè)試代碼寫完,就可以打開postman去做測(cè)試了。
(注:搜索 postman下載 即可在官網(wǎng)上下載postman軟件)
測(cè)試結(jié)果如圖:
9.結(jié)束語(yǔ):
至此,搭建springboot + mybatis 的Java后臺(tái)項(xiàng)目已經(jīng)結(jié)束。。
附上該項(xiàng)目示例的github地址:https://github.com/StephenChen1/demoproject.git
到此這篇關(guān)于IDEA創(chuàng)建springboot + mybatis項(xiàng)目全過(guò)程的文章就介紹到這了,更多相關(guān)idea 創(chuàng)建springboot mybatis過(guò)程內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法2. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析3. 淺談python出錯(cuò)時(shí)traceback的解讀4. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法5. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼6. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解7. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題8. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向9. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解10. Nginx+php配置文件及原理解析
