spring boot(二): spring boot+jdbctemplate+sql server

前言

小项目或者做demo时可以使用jdbc+sql server解决即可,这篇就基于spring boot环境使用jdbc连接sql server数据库,和spring mvc系列保持一致。 在spring boot中使用jdbc 连接sql server数据只需要引入两个jar:spring-boot-starter-jdbc、spring-boot-starter-data-jpa

项目结构

和上篇spring boot入门保持相同

pom.xml

<dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>        <!--<exclusions>-->            <!--<exclusion>-->                <!--<groupId>org.springframework.boot</groupId>-->                <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->            <!--</exclusion>-->        <!--</exclusions>-->    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-cache</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-jdbc</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-data-jpa</artifactId>        <version>1.5.4.RELEASE</version>    </dependency>

</dependencies>

Application.java、Dao、Service、model

1、Application.java

@SpringBootApplication(scanBasePackages = "com.autohome")
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args){
        System.out.println("server is running at 8080....");
        SpringApplication.run(Application.class,args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
}

2、Dao

package com.autohome.dao;

import com.autohome.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<User> listAllUser() {
        List<User> list = jdbcTemplate.query("select * from t_userinfo",new User());
        return list;
    }

    public int insertUser(final User user) {
        int result = jdbcTemplate.update("insert into t_userinfo (name,address) VALUES (?,?)", new PreparedStatementSetter() {
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1,user.getName());
                ps.setString(2,user.getAddress());
            }
        });

        return result;
    }

    public int updateUser(final User user) {
        int result = jdbcTemplate.update("UPDATE t_userinfo set name=?,address=? where id=?", new PreparedStatementSetter() {
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1,user.getName());
                ps.setString(2,user.getAddress());
                ps.setInt(3,user.getId());
            }
        });

        return result;
    }

    public int deleteUser(int id) {
        int result = jdbcTemplate.update("delete from t_userinfo where id=?",new Object[]{id},new int[]{Types.INTEGER});
        return result;
    }
}

3、Service

package com.autohome.service;

import com.autohome.dao.UserDao;
import com.autohome.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserDao userDao;

    public List<User> listAllUser(){
        return userDao.listAllUser();
    }

    public int insertUser(User user){
        return userDao.insertUser(user);
    }

    public int updateUser(User user){
        return userDao.updateUser(user);
    }

    public int deleteUser(int id){
        return userDao.deleteUser(id);
    }

}

4、Controller

package com.autohome.controller;

import com.autohome.model.User;
import com.autohome.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by zhangfei on 2017/6/22.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @ResponseBody
    @RequestMapping("/detail")
    public  User detail(Integer id){
        User user=new User();
        user.setId(id);
        user.setName("zhangsan");
        user.setAddress("china");
        return user;
    }

    @Autowired
    UserService userService;

    @ResponseBody
    @RequestMapping("/list")
    public List<User> list(){
        List<User> list = userService.listAllUser();
        System.out.println("size:"+list.size());
        return list;
    }

    @RequestMapping(value="/insert",method = RequestMethod.POST)
    public String insertUser(String name,String address){
        User user =new User();
        user.setName(name);
        user.setAddress(address);

        int result = userService.insertUser(user);
        if(result>0){
            return "{\"returncode\":0,\"message\":\"success\"}";
        }else{
            return "{\"returncode\":0,\"message\":\"error\"}";
        }

    }

}

 

 

时间: 2024-08-10 21:30:32

spring boot(二): spring boot+jdbctemplate+sql server的相关文章

基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD

完成一个RESTful服务,提供几个访问接口,用来操作较简单的联系人信息,数据保存在Sql Server数据库中. 1.使用STS创建工程. 使用STS创建RESTful工程,可以参考: <用Spring Tools Suite(STS)开始一个RESTful Web Service><SpringBoot构建RESTful service完成Get和Post> 新建项目时的Project Name,Group,Atifact,Package这些参数按照实际要求填. 项目引入依赖w

Spring连接MySQL、Oracle和SQL Server的数据库运动连接属性

在配置文件applicationContext.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" xsi:schemaLocation=&

Spring MVC(二)--Spring MVC登陆实例

本文通过一个简单的登陆实例实现Spring MVC的流程,同时整合 MyBatis使用,流程是这样的: 1.访问一个URL进入登陆界面 2.输入正确的用户名和密码,成功则进入index页面,否则留在登陆页 一.配置web.xml 创建好WEB项目之后的第一步就是配置web.xml文件 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" xmlns=&

SQL Server 性能优化实战系列(二)

SQL Server datetime数据类型设计.优化误区 一.场景 在SQL Server 2005中,有一个表TestDatetime,其中Dates这个字段的数据类型是datetime,如果你看到表的记录如下图所示,你最先想到的是什么呢? (图1:数据列表) 你看到这些数据,是不是觉得这样的设计既浪费了存储空间,又使得这个列的索引增大,查询起来更慢,你也想使用一些其它的数据类型来代替这个datetime吧? 其实大家都是这么想的,这个方向是100%正确的,但是在写这篇文章以前,我进入了两

SQL Server调试存储过程

一.   调试SQL   Server   2000 1.   设置帐户. <1>   在windows服务中找到MSSQLSERVER,双击弹出对话框. <2>   选择“登陆”选项卡,选中“此帐户”,输入一个管理员帐户和密码. <3>   重启服务. 2.   在查询分析器执行单步调试. <1>   在查询分析器中,右键单击存储过程,选择“调试”. 二.   VS2005本地调试Sql   Server   2005 1.   打开VS2005,单击&l

SQL Server报“GUID应包含带4个短划线的32位数”

转自:http://www.seayee.net/article/info_106.html 最近在配置一台服务器的MS SQL Server 2005的维护计划自动备份数据库,能创建维护计划,但设置了运行时间后,保存就提示“GUID 应包含带 4 个短划线的 32 位数(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)”错误,很不爽! 上网看看有没有解决办法吧,首先查到的是微软的帮助和支持的一篇<当您试图保存 SQL Server 管理 Studio 中的维护计划时的

ogg实现oracle到sql server 2005的同步

一.源端(oracle)配置1.创建同步测试表create table gg_user.t01(name varchar(20) primary key);create table gg_user.t02(id int primary key,name varchar(20));2.添加定义文件(是异构之间的传输,需要转换字段类型等处理需用到defgen工具生成定义文件)GGSCI (kermart) 4> edit params defgendefsfile D:\ggate\dirdef\t

delphi连接sql server的字符串2011-10-11 16:07

delphi连接sql server的字符串2011-10-11 16:07 一.delphi连接sql server 放一个连接组件 ADOConnection, 其它组件TADODataSet,TADOQuery等的connection指向ADOConnection就可以了. 你可以双击ADOConnection,使用它的向导.也可以使用下面的代码 function OpenADOConn:boolean; begin result:=false; try with ADOConnectio

33. PowerShell -- SQL Server的使用

PowerShell --  SQL Server的使用 (1) 一.概述 SQL Server 2012 提供了一个名为 sqlps 的 Windows PowerShell 模块,该模块用于将 SQL Server 组件导入到 Windows PowerShell 2.0 环境或脚本中.sqlps 模块提供一组 SQL Server cmdlet ,支持各种操作,如运行包含 Transact-SQL 或 XQuery 语句的 sqlcmd 脚本. 二.加载模块 1.SQL Server 20