【问题标题】:Creating a simple web application with Eclipse, Java, Gradle, Wildfly, Hibernate JPA, Spring and Angular使用 Eclipse、Java、Gradle、Wildfly、Hibernate JPA、Spring 和 Angular 创建一个简单的 Web 应用程序
【发布时间】:2020-04-22 23:51:19
【问题描述】:

我在 Eclipse 中创建了几个项目,这些项目是关于如何使用各种技术组合创建简单的 Web 应用程序的在线示例。我目前正在使用 Java 11、Eclipse IDE(版本 4.12.0)、Wildfly 17、Gradle 5.6、Hibernate 5.4.4 和带有 Primefaces 7.0 的 JSF。一切都很好,但我想要更多。

有没有一种简单的方法可以使用带有 Hibernate 的 Spring 框架将我的 EJB 项目转换为 EJB,并通过 RESTful Web 服务正确地将我的方法公开给 UI?之后我想用 Angular MVC 替换我的 JSF。

我发现很难在网络上为我的魔法组合获得适当的信息。

我的 Eclipse 项目结构是:

  1. DEMO - 我的主要项目 (EAR)
  2. DemoCORE - 嵌套后端项目 (EJB)
  3. DemoUI - 嵌套前端项目 (WAR)

我的 EJB 依赖项:

dependencies {
    compile group: 'javax', name: 'javaee-api', version: '8.0'
    compile group: 'org.hibernate', name: 'hibernate-core', version: '5.4.4.Final'
    compile group: 'org.hibernate', name: 'hibernate-validator', version: '6.0.17.Final'
    compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.4.4.Final'
    compile group: 'org.hibernate', name: 'hibernate-annotations', version: '3.5.6-Final'
    compile group: 'org.springframework.boot', name: 'spring-boot', version: '2.2.2.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.2.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.2.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-rest', version: '2.2.2.RELEASE'
    compile group: 'org.springframework.data', name: 'spring-data-commons', version: '2.2.3.RELEASE'
}

通过设置这些依赖项,我可以在 EJB 项目中的任何位置调用 Spring 方法。

Users DAO 的简单界面:

@Remote
public interface UsersDAORemote {
    public User create(User user);
    public List<User> create(List<User> users);
    public User update(User user);
    public List<User> update(List<User> users);
    public void remove(User user);
    public void remove(List<User> users);
    public void removeById(Integer id);
    public void removeByIdList(List<Integer> idList);
    public User getUserById(Integer id);
    public List<User> getUserList();
    public List<User> getUserListByIdList(List<Integer> idList);
    public List<User> getUserListByCategoryId(Integer id);
    public List<User> getUserListByCategoryIdList(List<Integer> idList);
    public List<User> getUserListByGroupId(Integer id);
    public List<User> getUserListByGroupIdList(List<Integer> idList);
    public boolean getUserAuthentication(String username, String password);
}

用户 DAO 实现:

@RunAs(value = "")
@PermitAll
@Stateless
public class UsersDAO implements UsersDAOLocal, UsersDAORemote {

    @PersistenceContext
    private EntityManager em;

    @Override
    public User create(User user) {
        em.persist(user);
        return user;
    }

    @Override
    public List<User> create(List<User> users) {
        List<User> uList = new ArrayList<User>();
        for (User u : users) {
            em.persist(u);
            uList.add(u);
        }
        if (uList.isEmpty()) {
            return new ArrayList<User>();
        }
        return uList;
    }

    @Override
    public User update(User user) {
        em.merge(user);
        return user;
    }

    @Override
    public List<User> update(List<User> users) {
        List<User> uList = new ArrayList<User>();
        for (User u : users) {
            em.merge(u);
            uList.add(u);
        }
        if (uList.isEmpty()) {
            return new ArrayList<User>();
        }
        return uList;
    }

    @Override
    public void remove(User user) {
        em.remove(user);
    }

    @Override
    public void remove(List<User> users) {
        for (User u : users) {
            em.remove(u);
        }
    }

    @Override
    public void removeById(Integer id) {
        em.remove(getUserById(id));
    }

    @Override
    public void removeByIdList(List<Integer> idList) {
        for (Integer id : idList) {
            if (getUserById(id) != null) {
                removeById(id);
            }
        }
    }

    @Override
    public User getUserById(Integer id) {
        if (id != null) {
            return em.find(User.class, id);
        } else {
            return null;
        }
    }

    @Override
    public List<User> getUserList() {
        return em.createNamedQuery("getUsersList", User.class).getResultList();
    }

    @Override
    public List<User> getUserListByIdList(List<Integer> idList) {
        List<User> uList = new ArrayList<User>();
        User u = null;
        if (!idList.isEmpty()) {
            for (Integer id : idList) {
                u = getUserById(id);
                if (u != null) {
                    uList.add(u);
                }
            }
        }
        if (uList.isEmpty()) {
            return new ArrayList<User>();
        }
        return uList;
    }

    @Override
    public List<User> getUserListByCategoryId(Integer id) {
        TypedQuery<User> query = em.createNamedQuery("getUsersListByCategoryId", User.class);
        query.setParameter("id_category", id);
        return query.getResultList();
    }

    @Override
    public List<User> getUserListByCategoryIdList(List<Integer> idList) {
        List<User> result = new ArrayList<User>();
        for (Integer id : idList) {
            if (id != null) {
                result.addAll(getUserListByCategoryId(id));
            }
        }
        if (result.isEmpty()) {
            return new ArrayList<User>();
        }
        return result;
    }

    @Override
    public List<User> getUserListByGroupId(Integer id) {
        TypedQuery<User> query = em.createNamedQuery("getUsersListByGroupId", User.class);
        query.setParameter("id_category", id);
        return query.getResultList();
    }

    @Override
    public List<User> getUserListByGroupIdList(List<Integer> idList) {
        List<User> result = new ArrayList<User>();
        for (Integer id : idList) {
            if (id != null) {
                result.addAll(getUserListByGroupId(id));
            }
        }
        if (result.isEmpty()) {
            return new ArrayList<User>();
        }
        return result;
    }

    @Override
    public boolean getUserAuthentication(String username, String password) {
        Query query = em.createNamedQuery("authenticateUser");
        query.setParameter("uName", username);
        query.setParameter("uPwd", password);
        return (boolean) query.getSingleResult();
    }
    
}

还有我的实体:

@NamedQueries({
    @NamedQuery(name = "getUsersList",  
        query = "select u from User u"  
    ),
    @NamedQuery(name = "getUsersListByCategoryId",  
        query = "select u from User u where u.categoryId = :categoryId"  
    ),
    @NamedQuery(name = "getUsersListByGroupId",  
        query = "select u from User u where u.groupId = :groupId"  
    ),
    @NamedQuery(name = "authenticateUser",  
        query = "select case when (count(u) > 0) then true else false end from User u where u.uName = :uName and u.uPwd = :uPwd"  
    )
})

@Entity
@Table(name="users")
public class User implements Serializable {
    private static final long serialVersionUID = 7927104765389722941L;
    
    @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) private Integer id;
    @NotNull @Column(name = "id_category", nullable = false, columnDefinition = "int default 0") private Integer categoryId;
    @NotNull @Column(name = "id_group", nullable = false, columnDefinition = "int default 0") private Integer groupId;
    @NotNull @Length(max=64) @Column(name = "username", nullable = false) private String uName;
    @NotNull @Length(max=128) @Column(name = "password", nullable = false) private String uPwd;
    
    
    @NotNull @Column(name = "add_datetime", nullable = false) private Date add_datetime;
    @NotNull @Column(name = "add_uid", nullable = false) private Integer add_uid;
    @Null @Column(name = "modify_datetime", nullable = true) private Date modify_datetime;
    @Null @Column(name = "modify_uid", nullable = true) private Integer modify_uid;
    
    public Integer getId() { return id; }
    
    public Integer getCategoryId() { return categoryId; }
    public void setCategoryId(Integer id) { this.categoryId = id; }
    
    public String getUsername() { return uName; }
    public void setUsername(String uName) { this.uName = uName; }
    
    public String getPwd() { return uPwd; }
    public void setPwd(String uPwd) { this.uPwd = uPwd; }
    
    public Date getAdd_datetime() { return add_datetime; }
    public void setAdd_datetime(Date add_datetime) { this.add_datetime = add_datetime; }
    public Integer getAdd_uid() { return add_uid; }
    public void setAdd_uid(Integer add_uid) { this.add_uid = add_uid; }
    public Date getModify_datetime() { return modify_datetime; }
    public void setModify_datetime(Date modify_datetime) { this.modify_datetime = modify_datetime; }
    public Integer getModify_uid() { return modify_uid; }
    public void setModify_uid(Integer modify_uid) { this.modify_uid = modify_uid; }
}

更新(2020-01-05):

我遵循了本教程:https://www.devglan.com/spring-boot/spring-boot-angular-example 并在我的 EJB 项目中实现了以下类。

UserController.java

@CrossOrigin(origins = "http://192.168.0.101:8080", maxAge = 3600)
@RestController
@RequestMapping({"/apiUsers"})
public class UserController {

    @Autowired
    private UserService userService;
    
    @PostMapping
    public User create(@RequestBody User user){
        return userService.createUser(user);
    }
    
    @GetMapping(path = {"/getUsersById/{id}"})
    public User getUserById(@PathVariable("id") Long id) {
        return userService.getUserById(id);
    }
    
    @PutMapping
    public User update(@RequestBody User user){
        return userService.update(user);
    }
    
    @DeleteMapping(path ={"/delById/{id}"})
    public void delete(@PathVariable("id") Long id) {
        userService.removeById(id);
    }
    
    @DeleteMapping
    public void delete(@RequestBody User user) {
        userService.remove(user);
    }
    
    @GetMapping(path ={"/getAll"})
    public List<User> getUsers() {
        return userService.getUserList();
    }
    
    @GetMapping(path ={"/getByCategroyId/{idCategory}"})
    public List<User> getUsersListByIdCategory(@PathVariable("idCategory") Long id) {
        return userService.getUserListByCategoryId(id);
    }
    
    @RequestMapping(value="/getByIdCategoryList/{idList}", method=RequestMethod.GET)
    @ResponseBody
    public List<User> getUsersListByIdCategoryList(@PathVariable("idList") List<Long> id) {
        return userService.getUserListByCategoryIdList(id);
    }
    
    @GetMapping(path ={"/getByIdGroup/{idGroup}"})
    public List<User> getUsersListByIdGroup(@PathVariable("idGroup") Long id) {
        return userService.getUserListByGroupId(id);
    }
    
    @RequestMapping(value="/getByIdGroupList/{idList}", method=RequestMethod.GET)
    @ResponseBody
    public List<User> getUsersListByIdGroupList(@PathVariable("idList") List<Long> id) {
        return userService.getUserListByGroupIdList(id);
    }
    
}

UserRepository.java

@Repository
public interface UserRepository extends CrudRepository<User, Long>{
    public List<User> findByIdCategory(Long idCategory);
    public List<User> findByIdGroup(Long idCategory);
    public Optional<User> findByUsernameAndPassword(String username, String password);
}

UserService.java

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public User createUser(User user) {
        userRepository.save(user);
        return user;
    }
    
    public User update(User user) {
        userRepository.save(user);
        return user;
    }
    
    public List<User> update(List<User> users) {
        userRepository.saveAll(users);
        return users;
    }
    
    public User remove(User user) {
        User u = getUserById(user.getId());
        if(u != null){
            userRepository.delete(u);
        }
        return u;
    }
    
    public void remove(List<User> users) {
        userRepository.deleteAll(users);
    }
    
    public User removeById(Long id) {
        User user = getUserById(id);
        if(user != null){
            userRepository.delete(user);
        }
        return user;
    }
    
    public void removeByIdList(List<Long> idList) {
        for (Long id : idList) {
            userRepository.deleteById(id);
        }
    }
    
    public User getUserById(Long id) {
        Optional<User> optional = userRepository.findById(id);
        return optional.orElseGet(null);
    }
    
    public List<User> getUserList() {
        return (List<User>) userRepository.findAll();
    }
    
    public List<User> getUserListByIdList(List<Long> idList) {
        List<User> result = new ArrayList<User>();
        if (!idList.isEmpty()) {
            for (Long id : idList) {
                Optional<User> u = userRepository.findById(id);
                if (u.isPresent()) {
                    result.add(u.get());
                }
            }
        }
        return result;
    }
    
    public List<User> getUserListByCategoryId(Long id) {
        return userRepository.findByIdCategory(id);
    }
    
    public List<User> getUserListByCategoryIdList(List<Long> idList) {
        List<User> result = new ArrayList<User>();
        if (!idList.isEmpty()) {
            for (Long id : idList) {
                List<User> u = userRepository.findByIdCategory(id);
                if (!u.isEmpty()) {
                    result.addAll(u);
                }
            }
        }
        return result;
    }
    
    public List<User> getUserListByGroupId(Long id) {
        return userRepository.findByIdGroup(id);
    }
    
    public List<User> getUserListByGroupIdList(List<Long> idList) {
        List<User> result = new ArrayList<User>();
        if (!idList.isEmpty()) {
            for (Long id : idList) {
                List<User> u = userRepository.findByIdGroup(id);
                if (!u.isEmpty()) {
                    result.addAll(u);
                }
            }
        }
        return result;
    }
    
    public boolean getUserAuthentication(String username, String password) {
        Optional<User> u = userRepository.findByUsernameAndPassword(username, password);
        if (u.isPresent()) {
            return true;
        } else {
            return false;
        }
    }
}

我已在我的 Wildfly 应用服务器上成功部署了 EAR,但在开始创建 GUI 之前,我不知道如何测试该服务是否真正工作。我已经在本地使用 Postman 应用发出了几个 GET 请求,例如 http://192.168.0.101:8080/DEMO/apiUsers/getAll,我得到的只是 404 错误。

我也尝试过重写 UserController,如本网站所述: http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/

UserController.java

@CrossOrigin(origins = "http://192.168.0.101:8080", maxAge = 3600)
@RestController
@RequestMapping({"/apiUsers"})
public class UserController {

    @Autowired
    private UserService userService;
    
    @RequestMapping(value = "/createUser/", method = RequestMethod.POST)
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getUsername());
 
        if (userService.doesUserExist(user)) {
            System.out.println("A User with name " + user.getUsername() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }
 
        userService.createUser(user);
 
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/getUserById/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }
    
    @GetMapping(path = {"/getUserById/{id}"})
    public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.getUserById(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @RequestMapping(value = "/updateUser/{id}", method = RequestMethod.PUT)
    public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
        System.out.println("Updating User " + id);
         
        User currentUser = userService.getUserById(id);
         
        if (currentUser==null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        
        currentUser.setUsername(user.getUsername());
        currentUser.setIdCategory(user.getIdCategory());
        currentUser.setIdGroup(user.getIdGroup());
        currentUser.setPwd(user.getPwd());
         
        userService.update(currentUser);
        return new ResponseEntity<User>(currentUser, HttpStatus.OK);
    }
    
    @RequestMapping(value = "/delById/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting User with id " + id);
 
        User user = userService.getUserById(id);
        if (user == null) {
            System.out.println("Unable to delete. User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
 
        userService.removeById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }
    
    @RequestMapping(value = "/getAll/", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getUsers() {
        List<User> users = userService.getUserList();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }
    
    @RequestMapping(value = "/getByCategroyId/{idCategory}", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getUsersListByIdCategory(@PathVariable("idCategory") Long id) {
        System.out.println("Fetching List<User> by category with id " + id);
        List<User> users =  userService.getUserListByCategoryId(id);
        if(users.isEmpty()){
            System.out.println("Unable to fetch list. List<User> by category " + id + " not found");
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);  
    }
    
    @RequestMapping(value = "/getByIdCategoryList/{idList}", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getUsersListByIdCategoryList(@PathVariable("idList") List<Long> idList) {
        System.out.println("Fetching List<User> by category with id " + idList);
        List<User> users =  userService.getUserListByCategoryIdList(idList);
        if(users.isEmpty()){
            System.out.println("Unable to fetch list. List<User> by category list not found");
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);  
    }
    
    @RequestMapping(value = "/getByIdGroup/{idGroup}", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getUsersListByIdGroup(@PathVariable("idGroup") Long id) {
        System.out.println("Fetching List<User> by category with id " + id);
        List<User> users =  userService.getUserListByGroupId(id);
        if(users.isEmpty()){
            System.out.println("Unable to fetch list. List<User> by category " + id + " not found");
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);  
    }
    
    @RequestMapping(value = "/getByIdGroupList/{idList}", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getUsersListByIdGroupList(@PathVariable("idList") List<Long> idList) {
        System.out.println("Fetching List<User> by category with id " + idList);
        List<User> users =  userService.getUserListByGroupIdList(idList);
        if(users.isEmpty()){
            System.out.println("Unable to fetch list. List<User> by category list not found");
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);  
    }
    
}

我仍然得到 404。

我可能在编码过程中遗漏了一些东西,甚至可能遗漏了应用服务器设置(Wildfly 17)。

【问题讨论】:

  • 按要求编辑。
  • 您是否尝试过除 getAll 之外的任何其他端点?请记住,如果您将请求映射值声明为“/getAll/”,然后尝试仅访问“/getAll”(请注意缺少的反斜杠),它将不起作用
  • 我也尝试过其他端点。它们都不起作用。他们都返回 404。我知道那个特定的斜线。

标签: java angular hibernate spring-boot


【解决方案1】:

我没有将您的 EJB 直接转换为 Spring 代码的答案。 但是考虑到您有现有的数据库,您可以将该数据库导入 WaveMaker,我们为 CRUD 操作生成 Spring 代码和 REST API。 See this how to article。 您已经在 DB 上拥有 can be written as queries 的命名查询,WaveMaker 也会生成 REST API 来调用这些查询。 对于 CRUD 操作,在 WaveMaker 中使用 List、Forms、Tables 创建 UI 很简单。我们为 UI 生成 Angular 代码。 您可以免费评估该工具。

【讨论】:

    猜你喜欢
    • 2014-11-07
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多