1. 程式人生 > >springboot 框架 mybatis逆向工程

springboot 框架 mybatis逆向工程

第一步建立maven專案  配置pom.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="DB2Tables" targetRuntime="MyBatis3">
		<!-- 配置資料連線資訊 -->
		<!-- 	去掉註釋suppressDate是去掉生成日期那行註釋suppressAllComments是去掉所有的註解 -->
		<commentGenerator>
			<property name="suppressDate" value="true" />
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8" userId="root"
			password="123456">
		</jdbcConnection>

		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- 指定java bean生成的位置 -->
		<javaModelGenerator targetPackage="com.db.crud.bean"
			targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!-- 指定sql對映檔案生成的位置 -->
		<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<!-- 指定dao介面生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.db.crud.dao" targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<!-- 指定每個表的生成策略 -->
		<table tableName="user" domainObjectName="User"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false"></table>
	</context>
</generatorConfiguration>

第二步: 新建application.properties

server.port=8080

#DB Configuration
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

#JPA Configuration
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
sprign.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.html

第三步:配置mbg.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="DB2Tables" targetRuntime="MyBatis3">
		<!-- 配置資料連線資訊 -->
		<!-- 	去掉註釋suppressDate是去掉生成日期那行註釋suppressAllComments是去掉所有的註解 -->
		<commentGenerator>
			<property name="suppressDate" value="true" />
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8" userId="root"
			password="123456">
		</jdbcConnection>

		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- 指定java bean生成的位置 -->
		<javaModelGenerator targetPackage="com.db.crud.bean"
			targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!-- 指定sql對映檔案生成的位置 -->
		<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<!-- 指定dao介面生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.db.crud.dao" targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<!-- 指定每個表的生成策略 -->
		<table tableName="user" domainObjectName="User"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false"></table>
	</context>
</generatorConfiguration>

第四步:在測試包下建立mybatis逆向工程測試類 然後執行檔案

package com.db.Maven_ssm;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MBGTest {
	public static void main(String[] args) throws IOException, Exception {
		 List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   File configFile = new File("mbg.xml");
		   ConfigurationParser cp = new ConfigurationParser(warnings);
		   Configuration config = cp.parseConfiguration(configFile);
		   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		   myBatisGenerator.generate(null);
	}
}

第五步:F5重新整理專案,mybatis逆向工程成功

第六步:建立springboot啟動類(注意springboot啟動類起的包名要高於其他層比如Controller,dao,pojo,service..)

package com.db;

import java.util.Properties;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.github.pagehelper.PageHelper;

@SpringBootApplication
//讓其掃描dao層介面
@MapperScan("com.db.crud.dao")
public class app {
	//#pagehelper分頁配置 
	 @Bean
	    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("dialect", "ssm_crud"); // 配置mysql資料庫
	        pageHelper.setProperties(p);
	        return pageHelper;
	    }
//啟動類
	public static void main(String[] args) {
		// TODO Auto-generated method stub
   SpringApplication.run(app.class, args);
	}

}

 第七步:配置application.yml檔案

server:
  port:  8080
spring:
  profiles:
    active: dev
    datasource:
    url: jdbc:mysql://localhost:3306/ssm_crud
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    # 使用druid資料來源
    type: com.alibaba.druid.pool.DruidDataSource
#公共配置與profiles選擇無關 mapperLocations指的路徑是src/main/resources
mybatis:
  typeAliasesPackage: com.db.crud.bean
  mapperLocations: classpath:mapper/*.xml
#pagehelper分頁外掛
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
#注意 “:”後面跟空格,要不會報錯

 第八步:service.impl  實現類加入@service註解(dao層 ,service層不需要加註解了)

package com.db.crud.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.db.crud.bean.User;
import com.db.crud.dao.UserMapper;
import com.db.crud.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired //這個註解是屬業spring的)或者使用@Resource裝配可以減少了與spring的耦合
    UserMapper userMapper;
	@Override
	public int deleteByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return userMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(User record) {
		// TODO Auto-generated method stub
		return userMapper.insert(record);
	}

	@Override
	public int insertSelective(User record) {
		// TODO Auto-generated method stub
		return userMapper.insertSelective(record);
	}

	@Override
	public User selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		System.out.println("=============="+userMapper);
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(User record) {
		// TODO Auto-generated method stub
		return userMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(User record) {
		// TODO Auto-generated method stub
		return userMapper.updateByPrimaryKey(record);
	}

}

第九步:建立Controller類

package com.db.crud.Controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.db.crud.bean.User;
import com.db.crud.service.UserService;

@Controller
@RequestMapping("/user")
public class userController {

	@Autowired
	UserService userService;
	@RequestMapping("/show")
	@ResponseBody   //返回json資料
	public User login(Model model){
		
		User user=userService.selectByPrimaryKey(1);
		return user;
	}
	
}

最後測試是否成功: 啟動spring

 

顯示資料說明成功了