使用数据库优先方法创建spring启动项目需要哪些步骤?这里使用的数据库是mysql

fcipmucu  于 2021-07-15  发布在  Java
关注(0)|答案(1)|浏览(257)

我正在学习springboot(用于restapi)。我读过spring引导文档和其他教程,但都是基于使用实体创建数据库表(代码优先方法)。其中一个教程谈到了jboss(安装在eclipse marketplace中)。所以我遵循了教程,我能够从数据库表中创建实体、dao和pojo类。但是教程现在没有讨论如何执行积垢操作。所以我试着执行一些积垢操作,我得到了错误。
用户控制器

package com.example.dbfirst.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.dbfirst.entities.User;
import com.example.dbfirst.service.UserService;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("users/{id}")
    public User getUser(@PathVariable("id") int id) {

        return this.userService.getUser(id);

    }
}

用户服务

package com.example.dbfirst.service;

import javax.ejb.EJB;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dbfirst.dao.UserHome;
import com.example.dbfirst.entities.User;

@Service
public class UserService {

    //@Autowired
    private UserHome userHome;
    public User getUser(int id) {
        userHome=new UserHome();
        return this.userHome.findById(id);
    }
}

使用jboss和hibernate.cfg.xmluserhome的用户dao类

package com.example.dbfirst.dao;
// Generated 25-Mar-2021, 4:50:30 pm by Hibernate Tools 5.2.12.Final

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;

import com.example.dbfirst.entities.User;

@Stateless
public class UserHome {

    private static final Log log = LogFactory.getLog(UserHome.class);

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(User transientInstance) {
        log.debug("persisting User instance");
        try {
            entityManager.persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(User persistentInstance) {
        log.debug("removing User instance");
        try {
            entityManager.remove(persistentInstance);
            log.debug("remove successful");
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public User merge(User detachedInstance) {
        log.debug("merging User instance");
        try {
            User result = entityManager.merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public User findById(Integer id) {

        log.debug("getting User instance with id: " + id);
        try {
            User instance = entityManager.find(User.class, id);
            log.debug("get successful");
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
}

用户实体

package com.example.dbfirst.entities;
// Generated 25-Mar-2021, 4:12:53 pm by Hibernate Tools 5.2.12.Final

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * User generated by hbm2java
 */
@Entity
@Table(name = "user", catalog = "mydb")
public class User implements java.io.Serializable {

    private Integer id;
    private String email;
    private String password;

    public User() {
    }

    public User(String email, String password) {
        this.email = email;
        this.password = password;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "email", length = 45)
    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "password", length = 45)
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

用户pojo类

package com.example.dbfirst.pojo;
    // Generated 25-Mar-2021, 4:09:56 pm by Hibernate Tools 5.2.12.Final

    /**
     * User generated by hbm2java
     */
    public class User implements java.io.Serializable {

        private Integer id;
        private String email;
        private String password;

        public User() {
        }

        public User(String email, String password) {
            this.email = email;
            this.password = password;
        }

        public Integer getId() {
            return this.id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getEmail() {
            return this.email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getPassword() {
            return this.password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

    }

现在,当我从 Postman 处调用“users/id”时,我得到以下错误:

"status": 500,
"error": "Internal Server Error",
"message": "Cannot invoke \"javax.persistence.EntityManager.find(java.lang.Class, Object)\" because \"this.entityManager\" is null",
 "path": "/users/2"

我可能错过了一些步骤,或者我可能在某个地方犯了一些错误。如果您能告诉我使用数据库优先方法(直到crud操作)创建spring引导项目所需的步骤,那将非常有用。你也可以分享一些文章/链接。我已经看过很多文章来解决这个问题。我希望采用数据库优先方法的原因如下:
我想将数据库部分与spring项目编码部分分开(不想在这样的级别上混合它们)
我想单独设计数据库,完全独立于项目类型。
谢谢你的帮助。

bihw5rsg

bihw5rsg1#

在您的情况下,请遵循以下步骤:
首先创建数据库表。
禁用“自动创建”和“自动更新”。
代码中有很多不必要的行。
仅创建实体类(稍后添加dto)
从控制器直接访问存储库(删除服务层以供以后添加)
如果将列正确地Map到实体字段,则会导致错误(使用@cloumn(name=“name”))以避免错误,并使用@id作为主键。
您可以参考:禁用springdatajpa中的自动更新
https://spring.io/guides/gs/accessing-data-jpa/

相关问题