美文网首页
Spring中级课程第二课

Spring中级课程第二课

作者: 明明找灵气 | 来源:发表于2016-11-17 16:39 被阅读0次

一. sql

  1. 数据库基本操作CRUD(关键字大小写都可以,尽量大写)
    插入INSERT INTO table_name(列1,列 2,。。。)VALUES(值1,值2,...)
    insert into user(name,password) values('a1','b1')
    选择 SELECT */列名 FROM 表名称
    SELECT id,name FROM toutiao.user 两列
    SELECT * FROM toutiao.user 整个表
    SELECT * FROM user WHERE id > 1 ORDER BY id desc LIMIT 2, 3; 以id降序,偏移2,选3个
    更新UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
    update user set password = "aa1" where id =1;
    条件语句一般选主键域,或者唯一值的域
    删除 DELET FROM 表名称 WHERE 列名称 = 值
  2. JDBC:java数据库连接
    基本操作流程:
    a. 加载驱动
    b. 创建数据库链接
    c. 创建Statement对象
    d. 执行SQL获取数据(使用mybatis,只需关注这一步)
    e. 数据转化
    f. 资源释放
  3. mybatis配置
    ** mybatis 中文简介网站**
    逻辑过程:
  • 应用需要和数据库交互,所以要配个数据库
#<!--application.properties文件-->
spring.datasource.url=jdbc:mysql://localhost:3306/toutiao?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=tangxueming
#不自动初始化
#spring.datasource.initialize=false
#如果启动web程序,需要在classpath中找
mybatis.config-location=classpath:mybatis-config.xml
  • 引用mybatis,所以要把mybatis引入pom.xml,加入依赖后自动下载,然后mybatis又要数据库的连接,所以加入两个依赖
<!--插入到pom.xml文件的<dependencies></depebdebcies>中间-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope></dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.1.1</version>
</dependency>
  • 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>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
    <!-- Continue going here -->
</configuration>
  • 测试:建4个文件,数据初始化sql文件,用户类文件,用户DAO接口,用户数据测试用例。路径:
    src/test/resources/init-schema.sql
    src/main/java/com.nowcoder.model/User.java
    src/main/java/com.nowcoder.dao/UserDAO.java
    src/test/java/com.nowcoder/InitDatabaseTests.java
//init-schema.sql
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` ( 
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
 `name` varchar(64) NOT NULL DEFAULT '',
  `password` varchar(128) NOT NULL DEFAULT '',
  `salt` varchar(32) NOT NULL DEFAULT '',
  `head_url` varchar(256) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(128) NOT NULL DEFAULT '',
  `link` varchar(256) NOT NULL DEFAULT '',
  `image` varchar(256) NOT NULL DEFAULT '',
  `like_count` int NOT NULL,
  `comment_count` int NOT NULL,
  `created_date` datetime NOT NULL,
  `user_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//User.java 包含getter和setter,构造器,简单
//UserDAO.java
@Mapper
public interface UserDAO {
    String TABLE_NAME = "user";
    String INSET_FIELDS = "name, password, salt, head_url";
    String SELECT_FIELDS = "id, name, password, salt, head_url";
    //@Insert({"insert into user (name, password, slat, head_url) value ()"})
    @Insert({"insert into ", TABLE_NAME, "(", INSET_FIELDS,
            ") value (#{name}, #{password}, #{salt}, #{headUrl})"})
    int addUser(User user);
}
//InitDatabaseTests.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ToutiaoApplication.class)
@Sql("/init-schema.sql")
public class InitDatabaseTests {
   @Autowired
  UserDAO userDAO;
   @Test
   public void contextLoads() {
      Random random = new Random();
      for(int i = 0; i < 11; i++) { 
         User user = new User();
         user.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png",random.nextInt(1000)));
         user.setName(String.format("USER%d", i));
         user.setPassword("");
         user.setSalt("");
         userDAO.addUser(user);
           }
         }
}

相关文章

  • Spring中级课程第二课

    一. sql 数据库基本操作CRUD(关键字大小写都可以,尽量大写)插入INSERT INTO table_nam...

  • 程序员必修框架之Spring 3.0 MVC

    Spring3.0 MVC框架 类 型:中级教程 适合对象:学习完spring框架,对于spring MVC感兴趣...

  • Spring中级课程第三课

    库的下载网址,intellij新建的时候自动从该网址下载。 一. 注册 用户名合法性检测(长度,敏感词,重复,特殊...

  • Spring中级课程第一课

    一. 创建简单工程网页SpringBoot进入[SpringBoot网站][],选择自己需要的依赖(Web,Vel...

  • 2017-10-02

    中级班课程

  • 中级 词汇,语法课程Academic Vocabulary, G

    中级 词汇,语法课程 等级:中级进阶 40节课程中级到高级语法,通过合理的例句在重要词汇的语法应用和指导,还有通过...

  • cv2 问题 Build OpenCV with Inferen

    课程地址:intel 中级课程 openvino[https://openvinohackathon.51open...

  • 路彦安坚持分享40+1

    (焦点中级课程——咨询实操班分享1) 2020 08 16,今晚7:30—9:30,焦点中级课程第一...

  • 温和与柔软

    内观正念心灵成长课程中级班第十一次工作坊已经结束了,再有一次,中级课程就全部完成。从这次课程训练情况看,...

  • 日更(逻辑课)

    第二课 在百度云看到这个课程,觉得挺不错的,属于提升思维的课程,今天看到第二课,做一些记录 思维的提升会...

网友评论

      本文标题:Spring中级课程第二课

      本文链接:https://www.haomeiwen.com/subject/wxkdpttx.html