项目理解(四):数据库基础

本文介绍了使用MySQL Workbench创建数据库,列举了常见数据类型及CRUD操作。还讲述了无框架时的JDBC数据库操作步骤,重点介绍了流行的ORM框架MyBatis,包括其概念、配置、重要概念及事务,最后提及工程层次结构,如dao层、service层和web层的交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 使用MySQL Workbench 可操作性界面来创建数据库(入门工具)
  2. 数据库常见的数据类型:
    Int整数;
    Varchar指定最大多长的字符串(如密码等不知道有多长,指定最大长度);
    datetime时间的数据结构;
    float:浮点类型;
    text:比较大的文本。
  3. CRUD操作:增删改查操作:
  4. INSERT INTO table_name(列1,列2,….) VALUES(值1,值2)
  5. SELECT */列名称 FROM 表名称
  6. UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
  7. DELETE FROM 表名称 WHERE 列名称  = 值
  8. #insert into user(name,password) values ("liu","pa"); 
    #insert into user(name,password) values ("liu1","pa1"); 
    #insert into user(name,password) values ("liu2","pa2"); 
    #insert into user(name,password) values ("liu3","pa3"); 
    #insert into user(id,name,password) values (20,"liuze","pa");
    #insert into user(id,name,password) values (2,"liuze23","pa");
    #insert into user(id,name,password) values (3,"liuze34","pa");
    #insert into user(id,name,password) values (7,"liuze7","pa");
     
    select id,name from user ;
    select * from user where id =4;
    select *from user where id < 3 and id >1;
    select *from user where id between 1 and 3;
    select *from user where id < 7 and id >1 order by password asc;#升序为asc;降序为desc
    select *from user where id < 7 and id >1 order by password desc limit 2,2;#先降序排列,再偏移两个位置,再仅选择表中的2个元素
    
    update user set password = "711" where id = 7;
    select * from user where id =7;
    delete from user where id  = 7; 
    select * from user;
    
  9. 没有框架的情况下:JDBC数据库操作:
    加载驱动
    创建数据库连接
    创建Statement对象(表达式)
    执行SQL获取数据
    数据转化
    资源释放
  10. MyBatis是现如今最流行的ORM框架之一。ORM(Object Relational Mapping)对象关系映射模式是为了解决面向对象与关系数据库存在的互不匹配的现象的技术。ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。MyBatis支持普通的SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML注解用于配置和原始映射,将接口和JAVA的POJO(plain old java object,普通的java对象)映射成数据库中的记录。
     
  11. 如果是一些简单的SQL语句直接写在注解里面就可以了,如果是复杂的SQL语句可以写在XML中
  12.  

    MyBatis几个重要的概念:

    Mapper配置:可以使用基于XML的Mapper配置文件来实现,也可以使用基于java注解的MyBatis注解来实现

    Mapper接口:自行定义的一个数据操作接口。现在MyBtis可以自动为Mapper接口创建动态代理对象。Mapper中的方法通常与Mapper配置文件中的select、insert、update、delete等xml节点存在一一对应关系。

  13. 数据库中的事务:如支付宝转账,A扣除100,B接收100;要保障这两个事件都能完成。一个事务中,要么是整体都发生,要么就是都不成功。
     
  14. 工程层次结构:
              
  15. dao层与数据库交互:
    @Mapper
    public interface QuestionDAO {
        //此接口用来和数据库做交互,读数据库
        String TABLE_NAME = " question ";
        String INSERT_FIELDS = " title, content, created_date, user_id, comment_count ";
        String SELECT_FIELDS = " id, " + INSERT_FIELDS;
    
        //开始写SQL语句//通过注解来实现
        @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS,
                ") values (#{title},#{content},#{createdDate},#{userId},#{commentCount})"})
        int addQuestion(Question question);
    
        //通过XML查询,自动通过注解的方式去读取相应的xml
        List<Question> selectLatestQuestions(@Param("userId") int userId, @Param("offset") int offset,
                                             @Param("limit") int limit);
    
    }
    
    @Mapper
    public interface UserDAO {
        //此接口用来和数据库做交互,读数据库
        // 注意空格
        String TABLE_NAME = " user";
        String INSERT_FIELDS = " name, password, salt, head_url";
        String SELECT_FIELDS = " id, " + INSERT_FIELDS;
    
        //开始写SQL语句//通过注解来实现
        @Insert({"insert into ", TABLE_NAME, "(" , INSERT_FIELDS ,
                ") values (#{name},#{password},#{salt},#{headUrl})"})
        int addUser(User user);
    
        @Select({"select ", SELECT_FIELDS , " from" , TABLE_NAME , "where id = #{id}"})
        User selectById(int id);
    
        @Select({"select ", INSERT_FIELDS , "from" ,TABLE_NAME })
        List<User> selectAll();
    
        @Update({"update ", TABLE_NAME , " set password = #{password} where id = #{id}"})
        void updatePassword(User user);
    
        @Update({"update ", TABLE_NAME , " set password = #{id} "  ,"where id = #{id}"})
        void updatePasswordById(int id);
    
        @Delete({"delete from ",TABLE_NAME, "where id = #{id}"})
        void deleteById(int id);
    }
    
    QuestionDAO.xml:
    <?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.example.dao.QuestionDAO">
        <sql id="table">question</sql>
        <sql id="selectFields">id, title, content, comment_count,created_date,user_id
        </sql>
        <!--<resultMap type = "com.example.model.Question" id="Question">-->
        <!--</resultMap>-->
        <select id="selectLatestQuestions" resultType="com.example.model.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>
  16. 调用dao层的service层:
    @Service
    public class UserService {
    //    dao层读取数据库;此层调用dao层
        @Autowired
        UserDAO userDAO;
    
        public User getUser(int id) {
            return userDAO.selectById(id);
        }
        public List<User> getAllUsers(){
            List<User> list=new ArrayList<User>();
            for(int i = 0; i<15;i++){
                list.add(userDAO.selectById(i));
            }
            return  list;
        }
    }
    
    
    @Service
    public class QuestionService {
    //    dao层读取数据库;此层调用dao层
        @Autowired
        QuestionDAO questionDAO;
        public List<Question> getLatestQuestions(int userId, int offset, int limit){
            return questionDAO.selectLatestQuestions(userId, offset, limit);
        }
    }
    

     
  17. web层(Controller层):将数据库中的值读取出来,并与之交互,通过thymeleaf模板实现前端页面以及与数据的交互
    //@RestController里面的方法都以JSON格式输出,不需要其它额外配置
    //@RestController  注解相当于@ResponseBody和@Controller合在一起的作用,如果web层
    // 的类上使用了@RestController注解,就代表这个类中所有的方法都会以JSON的形式返
    // 回,也相当于JSON的一种快捷返回方式
    //@Controller代表输出内容到页面
    @Controller
    public class HomeController {
    //  controller层调用service层
    //  @RequestMapping提供路由信息;"/"路径的HTTP Request都会被映射到hello()方法上进行处理
    
        public static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
        @Autowired
        TestService testService;
        @Autowired
        UserService userService;
        @Autowired
        QuestionService questionService;
    
        @Autowired
        UserDAO userDAO;
    
        @Autowired
        QuestionDAO questionDAO;
    
    //web请求:controller----service-----DAO------Database
    //1通过路径传递
    //2通过请求参数传递
        @RequestMapping(path = {"/"} )
        @ResponseBody//直接返回体中定义的;不用ResponseBody也可以使用模板来进行返回
        public String index(HttpSession httpSession){
            logger.info("this method");
            return "Hello word!" + httpSession.getAttribute("msg") +
                    "service message" + testService.getMessage(12);
        }
    
        @RequestMapping(path = {"/index1"} , method = {RequestMethod.GET})
        public String index1(ModelMap map){
    //        List<Question> questionList = questionService.getLatestQuestions(0, 1, 2);
    ////        map.addAttribute("questions", questionList);
    //        List<ViewObject> viewObjects = new ArrayList<>();
    //        for(Question question :questionList){
    //            ViewObject vo = new ViewObject();
    //            vo.set("question", question);
    //            vo.set("user",userService.getUser(question.getUserId()));
    //        }
    //        map.addAttribute("viewObjects", viewObjects);
            return "letter";
    //        return "index";
    
        }
    
        @RequestMapping(path = {"/list"} , method = {RequestMethod.GET})
        public String listTest(ModelMap map){
    //        map.addAttribute("flag", "yes");
    //        map.addAttribute("users", DatabaseTest());
            map.addAttribute("users", userDAO.selectAll());
            map.addAttribute("message", "http://www.ityouknow.com");
            return "list";
        }
    
        @RequestMapping(path = {"/if"} , method = {RequestMethod.GET})
        public String ifTest(ModelMap map){
            map.addAttribute("flag", "yes");
    //        map.addAttribute("users", userService.getAllUsers());
            map.addAttribute("message", "http://www.ityouknow.com");
            return "hello";
        }
    
        public List<User> DatabaseTest() {
            List<User> list=new ArrayList<User>();
            Random random = new Random();
            for(int i = 0; i<15 ;  ++i){
                User user = new User();
                user.setHeadUrl(String.format("https://github.com/liuzewei1996", random.nextInt(100)));
                user.setName(String.format("USER%d", i));
                user.setPassword("111");
                user.setSalt("");
                list.add(user);
            }
            return list;
        }
    
    }

     












 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值