天天看点

spring-boot结合mysql整合mybatis

环境及工具:   系统:Mac 10.12.6     JDK版本: 1.8   maven 版本:3.0   开发工具:eclipse    数据库:mysql   语言:java

打开eclipse的Marketplace(Help—>Marketplace),安装spring-boot的工具环境。

如何确认安装完成呢?如下即可(新建项目可以看到spring start等选项):

接下来就创建项目,创建的时候可以任何jar依赖都不选择,我们可以自己向pom文件中添加,创建后的文件结构如下(已经删除了两个mvn文件):

接下来就是添加pom了,这是我的pom.xml <? xml   version = "1.0"   encoding = "UTF-8" ?> < project   xmlns = "http://maven.apache.org/POM/4.0.0"   xmlns:xsi =   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >      < modelVersion > 4.0.0 </ modelVersion >      < groupId > com.example </ groupId >      < artifactId > demo-boot </ artifactId >      < version > 0.0.1-SNAPSHOT </ version >      < packaging > jar </ packaging >      < name > demo-boot </ name >      < description > Demo project for Spring Boot </ description >      < parent >           < groupId > org.springframework.boot </ groupId >           < artifactId > spring-boot-starter-parent </ artifactId >           < version > 1.4.1.RELEASE </ version >      </ parent >      < properties >           < project. build. sourceEncoding > UTF-8 </ project. build. sourceEncoding >           < project. reporting. outputEncoding > UTF-8 </ project. reporting. outputEncoding >           < java. version > 1.8 </ java. version >           < mysql-connector. version > 5.1.21 </ mysql-connector. version >      </ properties >      < dependencies >           <!-- aop 引入 -->           < dependency >                < groupId > org.springframework.boot </ groupId >                < artifactId > spring-boot-starter-aop </ artifactId >           </ dependency >           <!-- cache 引入 -->           < dependency >                < groupId > org.springframework.boot </ groupId >                < artifactId > spring-boot-starter-cache </ artifactId >           </ dependency >           <!-- redis 引入 -->           < dependency >                < groupId > org.springframework.boot </ groupId >                < artifactId > spring-boot-starter-redis </ artifactId >           </ dependency >           < dependency >                < groupId > org.springframework.boot </ groupId >                < artifactId > spring-boot-starter </ artifactId >           </ dependency >           < dependency >                < groupId > org.springframework.boot </ groupId >                < artifactId > spring-boot-starter-test </ artifactId >                < scope > test </ scope >           </ dependency >           <!-- spring-boot web引入 -->           < dependency >                < groupId > org.springframework.boot </ groupId >                < artifactId > spring-boot-starter-web </ artifactId >           </ dependency >           <!-- mysql 驱动包引入 -->           < dependency >                < groupId > org.apache.tomcat </ groupId >                < artifactId > tomcat-jdbc </ artifactId >           </ dependency >           < dependency >                < groupId > mysql </ groupId >                < artifactId > mysql-connector-java </ artifactId >                < scope > runtime </ scope >                < version > 5.1.21 </ version >                <!-- <version>${mysql-connector.version}</version> -->           </ dependency >           <!-- mybatis 引入 -->           < dependency >                < groupId > org.mybatis.spring.boot </ groupId >                < artifactId > mybatis-spring-boot-starter </ artifactId >                < version > 1.1.1 </ version >           </ dependency >      </ dependencies >      < build >           < pluginManagement >                < plugins >                     < plugin >                          < artifactId > maven-compiler-plugin </ artifactId >                          < configuration >                               < source > 1.8 </ source >                               < target > 1.8 </ target >                          </ configuration >                     </ plugin >                </ plugins >           </ pluginManagement >           < plugins >                < plugin >                     < groupId > org.springframework.boot </ groupId >                     < artifactId > spring-boot-maven-plugin </ artifactId >                </ plugin >           </ plugins >      </ build > </ project >   在这个pom中,主要用到的是mysql驱动包、mybatis以及springboot-web包。

我们继续介绍项目的结构,

我们先来看看启动类(在写spring-boot的项目时,只有一个main,尽量不要有第二个main方法): package  com. example; import  org. springframework. boot. SpringApplication; import  org. springframework. boot. autoconfigure. EnableAutoConfiguration; import  org. springframework. boot. autoconfigure. SpringBootApplication; import  org. springframework. boot. web. servlet. ServletComponentScan; import  org. springframework. context. annotation. ComponentScan; @ SpringBootApplication @ ComponentScan( basePackages ={ "com.example"})  //扫描包下的所有组件,包括启动类、servlet等 @ ServletComponentScan( basePackages  = { "com.example"}) //扫描包下的组件,包括servlet、filter。 @ EnableAutoConfiguration //自动载入应用程序所需的所有Bean,当使用Exclude这个属性时,是禁止自动配置某个类 @ RestController public  class  DemoBootApplication {      @ GetMapping( value = "/")      public  String  index( HttpServletRequest  request){          return  "index hello world!";     }           public  static  void  main( String[]  args) {          SpringApplication. run( DemoBootApplication. class,  args);     } } 代码就不多解释了,继续下一个类,HelloWorldContoller.java: package  com. example. controller; import  javax. servlet. http. HttpServletRequest; import  org. apache. log4j. Logger; import  org. springframework. web. bind. annotation. GetMapping; import  org. springframework. web. bind. annotation. RestController; import  com. example. model. TestModel; @ RestController  //@RestController的意思就是controller里面的方法都以json格式输出,不用再写什么jackjson配置的了! public  class  HelloWorldController {      private  static  Logger  logger  =  Logger. getLogger( HelloWorldController. class);          @ GetMapping( value = "index")      public  String  index( HttpServletRequest  request){          logger. info( "index hello world !");          return  "index hello world!";     }          @ GetMapping( value = "testObj")      public  TestModel  testObj( HttpServletRequest  request){          logger. info( "hello Test !");          TestModel  test  =  new  TestModel();          test. setId(1 L);          test. setTestName( "test name");          return  test;     } } (代码我就不介绍了,都有注释,大家应该能看明白)这样我们就完成了一个简单的可以访问的spring-boot的项目。

  来,我们启动一下项目。   我们右键选中项目,

启动项目,然后我们访问一下(这里要说明一下,我的application.properties配置文件端口改为了8082,所有我访问了8082,大家如果没有修改的话,端口应该是8080):

太好了,我们试试helloworldController.java的访问吧(自己试吧,我就不写实例了)。 ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- - 我们第一阶段完成了,那么接下来就是适用mybatis来访问mysql数据库了,让我们开始吧。 现在我们先来看一看application.properties文件吧, #server port set server.port: 8082 #mysql datasource set spring.datasource.url=jdbc:mysql://ip_addr:port/database_name?useUnicode=true&amp;amp;characterEncoding=utf-8&amp;amp;autoReconnect=true spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver 这些参数我就不介绍了,应该可以看明白,在这里有甚多的参数,我们安装了spring boot后,在这里写参数,就可以会有智能提示,很方便。 jar包我们已经在pom中写过了,没有问题,可以使用。那然后做什么呢? 对,链接数据库(类似于JDBC)代码,我们来看一下: package  com. example. config; import  javax. sql. DataSource; import  org. apache. ibatis. session. SqlSessionFactory; import  org. mybatis. spring. SqlSessionFactoryBean; import  org. mybatis. spring. annotation. MapperScan; import  org. springframework. boot. autoconfigure. EnableAutoConfiguration; import  org. springframework. boot. context. properties. ConfigurationProperties; import  org. springframework. context. annotation. Bean; import  org. springframework. context. annotation. ComponentScan; import  org. springframework. core. io. support. PathMatchingResourcePatternResolver; import  org. springframework. jdbc. datasource. DataSourceTransactionManager; import  org. springframework. transaction. PlatformTransactionManager; //@EnableAutoConfiguration @ ComponentScan @ MapperScan( "com.example.dao") //扫描有@Mapper注解的interface定义 public  class  DataSourceConfig {      // DataSource配置          @ Bean     @ ConfigurationProperties( prefix  =  "spring.datasource")      public  DataSource  dataSource() {          return  new  org. apache. tomcat. jdbc. pool. DataSource();     }      // 提供SqlSeesion(数据库事务操作相关的配置)     @ Bean      public  SqlSessionFactory  sqlSessionFactoryBean()  throws  Exception {          SqlSessionFactoryBean  sqlSessionFactoryBean  =  new  SqlSessionFactoryBean(); //创建SqlSessionFactoryBean类          sqlSessionFactoryBean. setDataSource( dataSource()); //设置数据库链接          //如果你不想写mapper.xml文件来实现功能的话,下面两行可以注释。 //      PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //      sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/example/mapper     @ Select( "select * from sm_user where 1=1 ")      List < SmUser >  searchUsers();           //    List<SmUser> searchUsers();           int  deleteByPrimaryKey( Long  id);      int  insert( SmUser  record);           int  insertSelective( SmUser  record);      SmUser  selectByPrimaryKey( Long  id);      int  updateByPrimaryKeySelective( SmUser  record);           int  updateByPrimaryKey( SmUser  record); } 对了,忘记了controller了,向各位献上code: package  com. example. controller; import  java. util. List; import  javax. servlet. http. HttpServletRequest; import  org. apache. log4j. Logger; import  org. springframework. beans. factory. annotation. Autowired; import  org. springframework. web. bind. annotation. GetMapping; import  org. springframework. web. bind. annotation. RequestMapping; import  org. springframework. web. bind. annotation. RestController; import  com. example. dao. SmUserMapper; import  com. example. model. SmUser; @ RestController  //@RestController的意思就是controller里面的方法都以json格式输出,不用再写什么jackjson配置的了! @ RequestMapping( "/sm/user") public  class  SmUserController {      private  static  Logger  logger  =  Logger. getLogger( SmUserController. class);     @ Autowired      private  SmUserMapper  smUserMapper;          @ GetMapping( value = "testObj")      public  List < SmUser >  testObj( HttpServletRequest  request){          logger. info( "hello Test !");          return  smUserMapper. searchUsers();     } } 在这个项目中我没有写service层的code,是因为暂时还没有必要,因为事务控制层还没有写,也没有太具体的业务case来让大家来理解,而且也没有配置数据库连接池。。。。所以就以简单的例子来说明了,不过下一篇文章就是数据库连接池和事务控制了,启动服务,然后访问:

  这样就完了。   总结一下,spring-boot简化了大部分开发准备工作,而且适用Mybatis的话,有多种方式,写起来也都非常方便。

  但是在这个例子中,我们发现,访问数据库有点慢,因它就像简单的jdbc操作一样,每一次都要打开和关闭数据库连接,并没有用到连接池来优化,也并没有用到配置事务相关的内容。 那么, 数据库连接池和事务控制这两块内容会在下一篇文章中讲解。