赞
踩
1、狂神说SpringMVC05:整合SSM框架 狂神系列笔记:狂神说Springboot笔记 - 时移之人 - 博客园
- <dependency>
- <groupId>com.microsoft.sqlserver</groupId>
- <artifactId>sqljdbc4</artifactId>
- <version>4.0</version>
- </dependency>
如果中央仓库拉不下来jar包,点击这里百度网盘 请输入提取码
,提取码0fcq,我将整个sqlserver驱动包文件夹上传了,你只要按照对应的路径复制就好。
网上手工教程Spring boot 连接 sqlserver_dianhuilu4947的博客-CSDN博客_springboot连接sqlserver数据库
刷新一下可以下载到。
注意: IP ALL/127.0.0.1和网卡IP的端口都要修改
有人采用 修改application.properties 为 application.yml SpringBoot连接SQLServer_哔哩哔哩_bilibili
spring: datasource: driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver url: jdbc:sqlserver://ip地址:端口;DatabaseName=数据库名 username: 用户名 password: 密码 maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 1 testWhileIdle: true testOnBorrow: true testOnReturn: true poolPreparedStatements: true maxOpenPreparedStatements: 20
我采用(application.properties)
- spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=数据库名
- spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
- spring.datasource.username=用户名
- spring.datasource.password=密码
- <!--springboot整合mybatis的依赖-->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.0.1</version>
- </dependency>
- <!--添加mybatis分页插件支持 根据需求可要可不要-->
- <dependency>
- <groupId>com.github.pagehelper</groupId>
- <artifactId>pagehelper</artifactId>
- <version>5.0.0</version>
- </dependency>
- #mapper配置文件
- mybatis.mapper-locations=classpath:mapper/*.xml
- mybatis.type-aliases-package=com.atl.erpcloud.mapper
- #开启驼峰命名
- mybatis.configuration.map-underscore-to-camel-case=true
注意:配置文件yml和properties文件格式不同
参见:SpringBoot项目中的目录结构,以及每个目录的作用是什么。_天霸地霸tua的博客-CSDN博客
在根目录下:
①工程启动类(ApplicationServer.java)在根目录的build包下
②实体类(domain)在根目录的domain下(我采用entity)
③数据访问层(dao)在根目录的repository下(我采用mapper)
④数据服务层(Service)在根目录的service下,数据服务的实现接口(serviceImpl)在根目录的service.impl下
⑤前端控制器(controller)在根目录的controller下
⑥工具类(utils)在根目录的utils下
⑦常量接口类(constant)在根目录的constan下
⑧配置信息类(config)在根目录的config下
⑨数据传输类(vo)在根目录的vo下。
资源文件的结构
根目录:src/main/resources
①项目配置文件:resources/application.yml
②.静态资源目录:resources/static/
——用于存放html、css、js、图片等资源
③视图模板目录:resources/templates/
——用于存放jsp、thymeleaf等模板文件
④mybatis映射文件:resources/mapper/(mybatis项目)
⑤mybatis配置文件:resources/mapper/config/(mybatis项目)
⑥国际化(i18n))置于i18n文件夹下
⑦spring.xml置于META-INF/spring文件夹下
⑧页面以及js/css/image等置于static文件夹下的各自文件下
- @SpringBootApplication
- //添加扫描mybatis的dao层接口,生成实现类
- @MapperScan(value = "com.baidu.mapper")
- public class Sbdemo2Application {
- public static void main(String[] args) {
- SpringApplication.run(Sbdemo2Application.class, args);
- }
- }
Springboot mybatis generate根据数据库表自动生成实体类、Mapper和Mapper.xml
Springboot+Mybatis+SQL Server自动生成实体类
POM.xml 修改
- <!-- mybatis自动生成插件 -->
- <dependency>
- <groupId>org.mybatis.generator</groupId>
- <artifactId>mybatis-generator-core</artifactId>
- <version>1.3.5</version>
- </dependency>
- <!-- Mybatis generator代码生成插件 配置 -->
- <plugin>
- <groupId>org.mybatis.generator</groupId>
- <artifactId>mybatis-generator-maven-plugin</artifactId>
- <version>1.3.1</version>
- <configuration>
- <!--generatorConfig.xml位置-->
- <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
- <overwrite>true</overwrite>
- <verbose>true</verbose>
- </configuration>
- <executions>
- <execution>
- <id>Generate MyBatis Artifacts</id>
- <goals>
- <goal>generate</goal>
- </goals>
- <phase>generate-sources</phase>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>com.microsoft.sqlserver</groupId>
- <artifactId>sqljdbc4</artifactId>
- <version>4.0</version>
- </dependency>
- </dependencies>
- </plugin>
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>
-
- <!--<properties resource="jdbc.properties"></properties>-->
- <!--数据库驱动包位置-->
- <classPathEntry location="C:\Users\liu\.m2\repository\com\microsoft\sqlserver\sqljdbc4\4.0\sqljdbc4-4.0.jar" />
-
- <context id="DB2Tables" targetRuntime="MyBatis3">
- <commentGenerator>
- <property name="suppressAllComments" value="true" />
- </commentGenerator>
-
- <!--数据库URL、用户名、密码-->
- <jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"
- connectionURL="jdbc:sqlserver://localhost:1433;DatabaseName=eggdemo" userId="sa" password="1q2w3e">
- </jdbcConnection>
-
-
- <!--生成模型包的位置 -->
- <javaModelGenerator targetPackage="com.atl.erpcloud.Entity"
- targetProject="./src/main/java">
- <property name="enableSubPackages" value="true" />
- <property name="trimStrings" value="true" />
- </javaModelGenerator>
-
- <!--生成映射文件的包名和位置-->
- <sqlMapGenerator targetPackage="Mapping" targetProject="./src/main/resources">
- <property name="enableSubPackages" value="false" />
- </sqlMapGenerator>
-
- <!--生成映射dao(Mapper)的包名和位置-->
- <javaClientGenerator type="XMLMAPPER"
- targetPackage="com.atl.erpcloud.Mapper" targetProject="./src/main/java">
- <property name="enableSubPackages" value="true" />
- </javaClientGenerator>
-
- <!--需要生成那些数据库(更改tableName和domainObjectName)-->
- <table tableName="bom_structure" domainObjectName="BomBom" enableCountByExample="false" enableUpdateByExample="false"
- enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" >
- </table>
-
- </context>
- </generatorConfiguration>
双击执行插件
提示错误:
- [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.1:generate (default-cli) on project erpcloud: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.1:generate failed: Plugin org.mybatis.generator:mybatis-generator-maven-plugin:1.3.1 or one of its dependencies could not be resolved: Failed to collect dependencies at org.mybatis.generator:mybatis-generator-maven-plugin:jar:1.3.1 -> com.microsoft.sqlserver:sqljdbc4:jar:4.0: Failed to read artifact descriptor for com.microsoft.sqlserver:sqljdbc4:jar:4.0: Could not transfer artifact com.microsoft.sqlserver:sqljdbc4:pom:4.0 from/to spring-snapshots (http://repo.spring.io/libs-snapshot): Authorization failed for http://repo.spring.io/libs-snapshot/com/microsoft/sqlserver/sqljdbc4/4.0/sqljdbc4-4.0.pom 403 Forbidden -> [Help 1]
- [ERROR]
- [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
- [ERROR] Re-run Maven using the -X switch to enable full debug logging.
- [ERROR]
- [ERROR] For more information about the errors and possible solutions, please read the following articles:
- [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException
删除pom中plugin中的
- <dependencies>
- <dependency>
- <groupId>com.microsoft.sqlserver</groupId>
- <artifactId>sqljdbc4</artifactId>
- <version>4.0</version>
- </dependency>
- </dependencies>
1、只用注解方式(删除掉UserMappper.xml文件即可。)
- package com.example.demo.dao;
-
- import java.util.List;
-
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Param;
- import org.apache.ibatis.annotations.Select;
-
- import com.example.demo.model.UserDomain;
-
- @Mapper
- public interface UserDao {
-
- @Insert("INSERT INTO t_user(name, password, phone) VALUES(#{name}, #{password}, #{phone})")
- int insert(@Param("name") String name, @Param("password") String password, @Param("phone") String phone);
-
-
- @Select("SELECT * FROM t_user ")
- List<UserDomain> selectUsers();
- }
2、@Repository和@Mapper注解问题
@Repository 来自Spring的注解
@Mapper 来自Mybatis的注解
在springboot 中,给mapper的接口上加上@Repository,无法生成相应的bean,从而无法@Autowired,这是因为spring扫描注解时,自动过滤掉了接口和抽象类,这种情况下可以在启动的类前加 上@MapperScan(“×××.×××.mapper”,从而使mapper可以自动注入,但是idea还会提示bean无法找到,但是不会影响运行
在使用Springboot环境下,如果结合了mybatis,在dao层上必须加@mapper与@Repository两个注解。尤其是@mapper,不可或缺;
而@Repository注解多用于实现类上。如果只是单独在接口上添加该方法会出现无法注入的情况;如果一定要只使用@Repository,可以在主方法上加@MapperScan(“com.xxx.xxx.dao”)
- @SpringBootApplication
- @MapperScan(
- basePackages = {"com.test.teinterface"},
- annotationClass = Mapper.class
- )
- public class InterfaceApplication extends SpringBootServletInitializer {
- public InterfaceApplication() {
- }
-
- public static void main(String[] args) {
- (new SpringApplicationBuilder(new Object[]{InterfaceApplication.class})).web(true).run(args);
- }
-
- protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
- SpringApplicationBuilder rst = builder.sources(new Class[]{InterfaceApplication.class});
- return rst;
- }
- }
暂时没有加接口类,直接实现BomInfoSerivce
- package com.atl.erpcloud.service;
- import com.atl.erpcloud.entity.BomInfo;
- import com.atl.erpcloud.mapper.BomInfoMapper;
- import com.github.pagehelper.PageHelper;
- import com.github.pagehelper.PageInfo;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- @Service
- public class BomInfoService {
- @Autowired
- private BomInfoMapper bomInfoMapper;
-
- public BomInfo getBomById(String model) {
- return bomInfoMapper.getBomById(model);
- }
-
- public int deleteById(String model) {
- return bomInfoMapper.deleteById(model);
- }
- public BomInfo addBom(BomInfo bomInfo) {
- int save = bomInfoMapper.insert(bomInfo);
- return bomInfo;
- }
-
- public int Update(BomInfo bomInfo) {
- return bomInfoMapper.updateBySelective(bomInfo);
- }
-
- public List<BomInfo> selectAll() {
- return bomInfoMapper.selectAll();
- }
- //分页查询
- //@Override
- public PageInfo<BomInfo> findAllModel(int pageNum, int pageSize) {
- PageHelper.startPage(pageNum, pageSize);
- List<BomInfo> bomDomains = bomInfoMapper.selectAll();
- PageInfo result = new PageInfo(bomDomains);
- return result;
- }
-
- }
@Autowired 相当于自动装配后的实例类的自动初始化参数,个人理解。
Postman
4、Spring Data JPA - Reference Documentation
5、SpringBoot+Mybatis 框架之 @SelectProvider注解方式搭建
6、基于 @SelectProvider 注解实现无侵入的通用Dao
Spring-data repositories use EntityManager beneath. Repository classes are just another layer for the user not to worry about the details. But if a user wants to get his hands dirty, then of course spring wouldn't mind.
That is when you can use EntityManager directly.
This section explains how to create a custom repository with Spring Boot.
Let us assume you have a Repository Class like AbcRepository
- interface AbcRepository extends JpaRepository<Abc, String> {
-
- }
You can create a custom repository like
- interface CustomizedAbcRepository {
- void someCustomMethod(User user);
- }
The implementation class looks like
- class CustomizedAbcRepositoryImpl implements CustomizedAbcRepository {
-
- @Autowired
- EntityManager entityManager;
-
-
- public void someCustomMethod(User user) {
- // You can build your custom query using Criteria or Criteria Builder
- // and then use that in entityManager methods
- }
- }
1、在根目录下的vue.config.js设置(不行,无效,不知道原因)
- devServer: {
- open: true, // npm run serve后自动打开页面
- host: '0.0.0.0', // 匹配本机IP地址(默认是0.0.0.0)
- port: 8081, // 开发服务器运行端口号
- proxy: {
- '/api': {
- target: 'http://127.0.0.1:8080/', // 代理接口地址
- secure: false, // 如果是https接口,需要配置这个参数
- changeOrigin: true, // 是否跨域
- pathRewrite: {
- '^/api': '/api' //需要rewrite的, 这里理解成以'/api'开头的接口地址,把/api代替target中的地址
- }
- }
- }
- },
2、改在config/index.js中设置(有效可以)
3、但是在jquery DataTable中还是有问题,如下:
list#:1 Access to XMLHttpRequest at 'http://127.0.0.1:8080/bom/bysql/1=1?_=1612838025177' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
问题原因:跨域资源共享 CORS 详解
解决方法增加拦截器:
- import com.tczmh.service.Interceptor.HeaderHandlerInterceptor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- @Configuration
- public class WebAppConfig implements WebMvcConfigurer {
-
- @Autowired
- private HeaderHandlerInterceptor headerHandlerInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- // 注册拦截器
- registry.addInterceptor(headerHandlerIntercepto).addPathPatterns("/**");
- }
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- @Component
- public class HeaderHandlerInterceptor implements HandlerInterceptor {
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
- // 这是要放行通过的域名 如果不限制用一个 * 也可以,就是不安全
- response.addHeader("Access-Control-Allow-Origin", "http://bz.tczmh.club");
- // 允许的方法 例如GET POST PUT DELETE,只要放行用过的
- response.addHeader("Access-Control-Request-Method", "POST");
- // 这个对应的是ajax里设置了header,例如存了token 或者 ontentType: "application/json"
- response.addHeader("Access-Control-Allow-Headers", "Content-Type");
- return true;
- }
-
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
-
- }
-
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
-
- }
- }
另外ajax调用如果用二级域名也有问题 会404,最好直接写全域名
- //另一个方法,未测试
- /*
- * @Configuration
- public class CrosConfig implements WebMvcConfigurer {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**")
- .allowedOrigins("*")
- .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
- .allowCredentials(true)
- .maxAge(3600)
- .allowedHeaders("*");
- }
- }
- * */
axios是一个基于 promise 的 HTTP 库,这样我们进行前后端对接的时候,使用这个工具可以提高我们的开发效率。
安装命令:
cnpm install axios --save
然后同样我们在main.js中全局引入axios。
- import axios from 'axios'
- Vue.prototype.$axios = axios //
- cnpm install bootstrap --save-dev
- cnpm install jquery --save-dev
- cnpm install popper.js --save-dev
import 'bootstrap'
引入jquery同理,可在main.js添加下面一行:
import $ from 'jquery'
- <script>
- import 'bootstrap/dist/css/bootstrap.min.css'
- import 'bootstrap/dist/js/bootstrap.min.js'
- </script>
如果Home.vue为Article.vue的父组件,那么想css作用于Article.vue,只需要在Home.vue添加上述两行import即可。
网上相关的教程或者博客很多,但是在这引入css和js文件的路径大多都是错的,正确的是从node_module之后开始算路径,如bootstrap/xxx/xxx/xxx.min.css,而不是'./node_modules/bootstrap/xxx/xxx/xx.min.css。
Vue系列4 - Vue+store 保存用户登录信息和退出登录
vuex + axios 做登录验证 并且保存登录状态
1、GET请求 使用RESTful风格api命名接口时,GET方法怎么传递多个参数
2、POST 请求 SpringBoot中Rest风格接口传递多个参数 SpringBoot中Rest风格接口传递多个参数_tianjidudao的博客-CSDN博客
部署SpringBoot大数据平台 部署SpringBoot大数据平台_LvJinYang的博客-CSDN博客
Vue父子组件传值的方法Vue父子组件传值的方法_lianwenxiu的博客-CSDN博客_父子组件传值
Vue混入(一)继承的实现方式Vue混入(一)继承的实现方式 - 简书
v-slot Vue新指令:v-slot | 码农网
springboot+vue前后端免费开源(重点参考)
1、org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题_写代码的蜗牛-CSDN博客
- #mapper配置文件
- mybatis.mapper-locations=classpath:Mapping/*.xml
- mybatis.type-aliases-package=com.atl.erpcloud.mapper
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。