美文网首页
AskMe项目数据库建立

AskMe项目数据库建立

作者: 当麻真实 | 来源:发表于2018-02-12 14:35 被阅读0次

建立数据库

使用的是可视化的Mysql工具Navicat,实现数据库AskMe,四个表的建立,分别为
user comment message question
使用SQL INSERT语句实现表项的插入,数据库课上学过,在此不再赘述


MyBatis集成

MyBatis是数据库相关的一个框架,配置好该框架我们就只需要关心数据库执行语句的编写,而不用再手动去做数据库连接等操作
集成方法(具体参考官网文档)
1. application.properties增加spring配置数据库链接地址

spring.datasource.url=jdbc:mysql://localhost:端口名/数据库名
spring.datasource.username=用户名
spring.datasource.password=密码
mybatis.config-location=classpath:mybatis-config.xml 
//上面那行是mybatis的配置文件的路径,之后会创建一个放在同一个文件夹下面
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2. pom.xml引入mybatis-spring-boot-starter和mysql-connector-java

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

3. 配置mybatis-config-xml文件

<?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. 官网

PS:至于如何导入依赖,使用IDEA时他发现没有你写的dependency时会自动弹出Auto import,这是点击他就会帮你导入了


DAO层——数据库操作层的建立

mybatis 有通过Mapper注解的方式来实现数据库操作的方法,比用XML形式的更为直观,方法如下,首先定义一个Mapper的接口,在里面放入Insert/Select/Update等注解,括号内加上语句,之后在Test文件或者需要操作的地方,用Autowired导入,即可进行执行

  • 定义Mapper
    其中#{}包裹的表示是user中相应的属性,这样只要传递user进来,就可以执行insert语句了(同理可以写其他的如select update delete语句
@Mapper
public interface userdao  {
    String tablename="user";
    String insertfield="name,password,salt,head_url";
    String selectfield="id,"+insertfield;
    @Insert({"INSERT INTO ",tablename,"("+insertfield+") Values(#{name},#{password},#{salt},#{head_url})"})
    int insertuser(User user);
}
  • Test文件执行
    该过程向user数据库中写入了五个用户
@RunWith(SpringRunner.class)
@SpringBootTest
public class DatabaseTests {
    @Autowired
    private userdao userdata;
    @Test
    public void databaseinsert() {
        Random random=new Random();
        for(int i=10;i<15;i++)
        {
            User s=new User();
            s.setName("User"+String.valueOf(i));
            s.setPassword("1");
            s.setSalt("2");
            s.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png",random.nextInt(1000)));
            userdata.insertuser(s);
        }
    }
}
  • 另一种方法,使用XML文件来执行数据库操作
  1. 要在resources文件夹下建立一个和Mapper文件路径完全一样的文件夹,然后建一个名字完全一样的XML文件
  2. 在XML文件中写入
    • 这些全都是要写在XML文件中的,第二段是resultMap映射关系的建立,type中填写的是你model中设计的类的完整路径名,id是自己取的名字,之后的select语句中写resultMap=你取的名字,就表示用这种类型的数据返回
    • 下面 column表示数据库结果的属性,property表示你model中Class的属性名。
    • 第三段中selec的id一定要和Mapper中的函数名一致
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.erika.askme.dao.questiondao">
    <sql id="table">question</sql>
    <sql id="selectFields">id, title, content, comment_count,created_date,user_id
    </sql>
    //第二段
    <resultMap type="com.erika.askme.model.Question" id="Question">
        <result column="id" property="id"/>
        <result column="title" property="title"/>
        <result column="content" property="content"/>
        <result column="comment_count" property="comment_count"/>
        <result column="created_date" property="created_date"/>
        <result column="user_id" property="user_id"/>
    </resultMap>
    //第三段
    <select id="selectLatestQuestions" resultMap="Question">
        SELECT
        <include refid="selectFields"/>
        FROM
        <include refid="table"/>

        <if test="userId != 0">
            WHERE user_id = #{userId}
        </if>
        ORDER BY id DESC
        LIMIT #{offset},#{limit}
    </select>
</mapper>
  1. 在Mapper函数中这样去传递参数
  • 函数名要和XML中的select id一致,用@Param("XML文件中参数名字") 和函数参数建立映射,XML中的参数名字就是用#{}包裹的部分,这样,调用是例如selectLatestQuestions(0,0,10)就是向select脚本传递了user_id=0等数据
 public interface questiondao {
 String tablename="question";
 List<Question> selectLatestQuestions(@Param("userId") int userId,@Param("offset") int offset,@Param("limit") int limit);
}
  1. 注意,XML中最好用resultMap来建立数据库列和函数属性之间的关系关系,如果简单地用resultMap会出现基本类型得到0或NULL的情况

个人主页的建立

编程规范 service调用DAO层,controller调用Service

  1. 编写Service来实现DAO和Controller之间的连接
@Service
public class QuestionService {
    @Autowired
    private questiondao questiondate;
    public List<Question> getquestionbydate(int userid,int offset,int limit)
    {
        return questiondate.selectLatestQuestions(userid,offset,limit);;
    }
}

2.向HTML文件中传递从Service(Service从DAO,DAO从数据库)拿来的数据,具体方法在上一篇文章中的Model传值,freemarker语言调用参数,方法等

相关文章

  • AskMe项目数据库建立

    建立数据库 使用的是可视化的Mysql工具Navicat,实现数据库AskMe,四个表的建立,分别为user co...

  • PMO卓越中心-项目数据库

    PMO项目数据库分为项目资料与项目度量值两部分。 1.项目资料的收集和管理 项目数据库是组织过程资产的重要组成部分...

  • AskMe项目 异步队列

    异步队列简单介绍 队列实现异步可以用单向队列,任务放到队列中,先进先出,或者使用优先队列,按照优先级来选择谁先执行...

  • # AskMe项目 邮件发送 Freemarker

    这次的邮件发送功能实现了,当用户登录时,向某个邮箱发送登录异常的邮件,还处在学习阶段,过程可供参考 发送邮箱的相关...

  • 2019-07-18

    由于明天全校停电,今天做了一下关于项目数据库备份工作。

  • 超详细 PowerDesigner 入门教学(项目数据库设计标准

    项目数据库设计标准步骤 一、数据需求分析 Creates a new modelimageimage 建好以后是这...

  • Blog 数据库

    Blog 项目数据库脚本:因为本人更熟悉sqlserver 所以就没用mysql CREATE TABLE [db...

  • 模特

    刘雯,中国模特。2009年,作为第一个亚洲模特登上维多利亚的秘密内衣秀。继2011年之后再度入榜男性网站ASKME...

  • MySQL执行SQL文件2006错误

    今天在拷贝公司项目数据库到本地数据库时报错:[Err] 2006 - MySQL server has gone ...

  • Springboot微信点餐系统

    1.项目数据库脚本需要用到的数据库表https://github.com/Gushifei/springboot_...

网友评论

      本文标题:AskMe项目数据库建立

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