ssm连接数据库

首先创建一个数据库,这里我使用的是navicat工具,如图所示

随便搞俩列,并给表取名为ceshi

在idea中连接数据库,如图所示

这里我使用的数据库是mysql,所以选择mysql选项

之后在弹出的界面中填写适当的数据,然后测试连接,测试成功 

 

此时数据库与idea已建立连接

安装如下三个插件,能为我们创建环境提供很多帮助

创建如下图所示包结构

 选中需要的数据库,点击mybatis-generator

在弹出的界面添加如下信息

此时会发现系统已经自动帮我们创建好了dao包与entity,并在Mapper包中已经添加好了相应的数据库映射。

在db.properties添加数据库信息

#mysql
jdbc.mysql.driver=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://localhost:3306/repair?characterEncoding=UTF-8&rewriteBatchedStatements=true
jdbc.mysql.username=root
jdbc.mysql.password=123456

在application.xml中添加如下的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.lxd.service"/>

    <!-- 引入外部资源文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 数据源的配置:德鲁伊连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基础配置 -->
        <property name="driverClassName" value="${jdbc.mysql.driver}"/>
        <property name="url" value="${jdbc.mysql.url}"/>
        <property name="username" value="${jdbc.mysql.username}"/>
        <property name="password" value="${jdbc.mysql.password}"/>
    </bean>
    <!-- mapper代理对象的扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描基础包-->
        <!-- 如果有多个基础包,可以使用逗号分隔-->
        <property name="basePackage" value="com.lxd.dao" />
        <!-- 注入SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!--Spring与mybatis的整合-->
    <!-- mybatis的SqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载mybatis的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 加载mapper映射文件,可以使用通配符-->
        <property name="mapperLocations" value="classpath:Mapper/*.xml"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 2.开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

在springmvc.xml中添加我们平常需要的驱动

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--包扫描-->
    <context:component-scan base-package="com.lxd.controller"></context:component-scan>

    <!--注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源问题-->
    <mvc:default-servlet-handler/>
    <!-- 文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件大小,单位为字节,大小为100MB -->
        <property name="maxUploadSize" value="104857600"/>
        <!-- 设置上传的字符编码-->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 设置缓存大小,大小为10KB-->
        <property name="maxInMemorySize" value="10240"/>
    </bean>
</beans>

在mybatis中添加驼峰映射与分页操作需要的代码

<?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>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--添加数据库信息打印-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 开启合理化分页-->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
</configuration>

跨域设置,在之后的前后端分离中需要使用,包结构如下(在此次配置中不需要)

CORSFilter

package com.lxd.filter;
/*这个文件是跨域设置*/
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        response.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        //response.setHeader("Access-Control-Allow-Origin","http://192.168.90.46:8848");
        //response.setHeader("Access-Control-Allow-Origin","*");//允许所有域名跨域访问该资源,根据项目实际需要可以设置允许特定的域名访问
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");//允许的跨域请求方式
      /*每次异步请求都发起预检请求,也就是说,发送两次请求。第一次是浏览器使用OPTIONS方法发起一个预检请求,第二次才是真正的异步请求,第一次的预检请求获知服务器是否
      允许该跨域请求:如果允许,才发起第二次真实的请求;如果不允许,则拦截第二次请求。*/
        response.setHeader("Access-Control-Max-Age", "0");//每次异步请求都发起预检请求,也就是说,发送两次请求。
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With,"
                + " If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires,"
                + " Content-Type, X-E4M-With,userId,token");//跨域请求允许包含的头
        response.setHeader("Access-Control-Allow-Credentials", "true");    //是否支持跨域,是否允许请求带有验证信息
        response.setHeader("XDomainRequestAllowed", "1");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    }
}

EncodingFilter

package com.lxd.tools;

import javax.servlet.http.HttpServlet;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;

public class EncodingFilter extends HttpServlet implements Filter
{
    private FilterConfig config = null;
    private String targetEncoding = "GBK";

    public void init(FilterConfig filterConfig)
    {
        this.config = filterConfig;
        this.targetEncoding = config.getInitParameter("encoding");
    }

    public void destroy()
    {
        config = null;
        targetEncoding = null;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain)
    {
        ServletRequest request = (ServletRequest) servletRequest;
        try
        {
            request.setCharacterEncoding(targetEncoding);
            filterChain.doFilter(servletRequest, servletResponse);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

}

之后我们进行测试

可以发现数据库已经连接成功,并成功查询到数据。

  • 9
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值