UserAccount

This commit is contained in:
2024-11-13 14:52:04 +01:00
parent c609f1ecc6
commit d4ff2d503e
34 changed files with 2148 additions and 6 deletions
@@ -0,0 +1,113 @@
package com.sasiedzi.event.domain;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* A UserAccount.
*/
@Entity
@Table(name = "user_account")
@SuppressWarnings("common-java:DuplicatedBlocks")
public class UserAccount implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "rel_user_account__user",
joinColumns = @JoinColumn(name = "user_account_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
private Set<User> users = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public UserAccount id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public UserAccount name(String name) {
this.setName(name);
return this;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return this.users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public UserAccount users(Set<User> users) {
this.setUsers(users);
return this;
}
public UserAccount addUser(User user) {
this.users.add(user);
return this;
}
public UserAccount removeUser(User user) {
this.users.remove(user);
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserAccount)) {
return false;
}
return getId() != null && getId().equals(((UserAccount) o).getId());
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "UserAccount{" +
"id=" + getId() +
", name='" + getName() + "'" +
"}";
}
}
@@ -0,0 +1,30 @@
package com.sasiedzi.event.repository;
import com.sasiedzi.event.domain.UserAccount;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the UserAccount entity.
*
* When extending this class, extend UserAccountRepositoryWithBagRelationships too.
* For more information refer to https://github.com/jhipster/generator-jhipster/issues/17990.
*/
@Repository
public interface UserAccountRepository extends UserAccountRepositoryWithBagRelationships, JpaRepository<UserAccount, Long> {
default Optional<UserAccount> findOneWithEagerRelationships(Long id) {
return this.fetchBagRelationships(this.findById(id));
}
default List<UserAccount> findAllWithEagerRelationships() {
return this.fetchBagRelationships(this.findAll());
}
default Page<UserAccount> findAllWithEagerRelationships(Pageable pageable) {
return this.fetchBagRelationships(this.findAll(pageable));
}
}
@@ -0,0 +1,14 @@
package com.sasiedzi.event.repository;
import com.sasiedzi.event.domain.UserAccount;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
public interface UserAccountRepositoryWithBagRelationships {
Optional<UserAccount> fetchBagRelationships(Optional<UserAccount> userAccount);
List<UserAccount> fetchBagRelationships(List<UserAccount> userAccounts);
Page<UserAccount> fetchBagRelationships(Page<UserAccount> userAccounts);
}
@@ -0,0 +1,67 @@
package com.sasiedzi.event.repository;
import com.sasiedzi.event.domain.UserAccount;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
/**
* Utility repository to load bag relationships based on https://vladmihalcea.com/hibernate-multiplebagfetchexception/
*/
public class UserAccountRepositoryWithBagRelationshipsImpl implements UserAccountRepositoryWithBagRelationships {
private static final String ID_PARAMETER = "id";
private static final String USERACCOUNTS_PARAMETER = "userAccounts";
@PersistenceContext
private EntityManager entityManager;
@Override
public Optional<UserAccount> fetchBagRelationships(Optional<UserAccount> userAccount) {
return userAccount.map(this::fetchUsers);
}
@Override
public Page<UserAccount> fetchBagRelationships(Page<UserAccount> userAccounts) {
return new PageImpl<>(
fetchBagRelationships(userAccounts.getContent()),
userAccounts.getPageable(),
userAccounts.getTotalElements()
);
}
@Override
public List<UserAccount> fetchBagRelationships(List<UserAccount> userAccounts) {
return Optional.of(userAccounts).map(this::fetchUsers).orElse(Collections.emptyList());
}
UserAccount fetchUsers(UserAccount result) {
return entityManager
.createQuery(
"select userAccount from UserAccount userAccount left join fetch userAccount.users where userAccount.id = :id",
UserAccount.class
)
.setParameter(ID_PARAMETER, result.getId())
.getSingleResult();
}
List<UserAccount> fetchUsers(List<UserAccount> userAccounts) {
HashMap<Object, Integer> order = new HashMap<>();
IntStream.range(0, userAccounts.size()).forEach(index -> order.put(userAccounts.get(index).getId(), index));
List<UserAccount> result = entityManager
.createQuery(
"select userAccount from UserAccount userAccount left join fetch userAccount.users where userAccount in :userAccounts",
UserAccount.class
)
.setParameter(USERACCOUNTS_PARAMETER, userAccounts)
.getResultList();
Collections.sort(result, (o1, o2) -> Integer.compare(order.get(o1.getId()), order.get(o2.getId())));
return result;
}
}
@@ -0,0 +1,183 @@
package com.sasiedzi.event.web.rest;
import com.sasiedzi.event.domain.UserAccount;
import com.sasiedzi.event.repository.UserAccountRepository;
import com.sasiedzi.event.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link com.sasiedzi.event.domain.UserAccount}.
*/
@RestController
@RequestMapping("/api/user-accounts")
@Transactional
public class UserAccountResource {
private static final Logger LOG = LoggerFactory.getLogger(UserAccountResource.class);
private static final String ENTITY_NAME = "userAccount";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final UserAccountRepository userAccountRepository;
public UserAccountResource(UserAccountRepository userAccountRepository) {
this.userAccountRepository = userAccountRepository;
}
/**
* {@code POST /user-accounts} : Create a new userAccount.
*
* @param userAccount the userAccount to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new userAccount, or with status {@code 400 (Bad Request)} if the userAccount has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("")
public ResponseEntity<UserAccount> createUserAccount(@RequestBody UserAccount userAccount) throws URISyntaxException {
LOG.debug("REST request to save UserAccount : {}", userAccount);
if (userAccount.getId() != null) {
throw new BadRequestAlertException("A new userAccount cannot already have an ID", ENTITY_NAME, "idexists");
}
userAccount = userAccountRepository.save(userAccount);
return ResponseEntity.created(new URI("/api/user-accounts/" + userAccount.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, userAccount.getId().toString()))
.body(userAccount);
}
/**
* {@code PUT /user-accounts/:id} : Updates an existing userAccount.
*
* @param id the id of the userAccount to save.
* @param userAccount the userAccount to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated userAccount,
* or with status {@code 400 (Bad Request)} if the userAccount is not valid,
* or with status {@code 500 (Internal Server Error)} if the userAccount couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/{id}")
public ResponseEntity<UserAccount> updateUserAccount(
@PathVariable(value = "id", required = false) final Long id,
@RequestBody UserAccount userAccount
) throws URISyntaxException {
LOG.debug("REST request to update UserAccount : {}, {}", id, userAccount);
if (userAccount.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, userAccount.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!userAccountRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
userAccount = userAccountRepository.save(userAccount);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, userAccount.getId().toString()))
.body(userAccount);
}
/**
* {@code PATCH /user-accounts/:id} : Partial updates given fields of an existing userAccount, field will ignore if it is null
*
* @param id the id of the userAccount to save.
* @param userAccount the userAccount to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated userAccount,
* or with status {@code 400 (Bad Request)} if the userAccount is not valid,
* or with status {@code 404 (Not Found)} if the userAccount is not found,
* or with status {@code 500 (Internal Server Error)} if the userAccount couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity<UserAccount> partialUpdateUserAccount(
@PathVariable(value = "id", required = false) final Long id,
@RequestBody UserAccount userAccount
) throws URISyntaxException {
LOG.debug("REST request to partial update UserAccount partially : {}, {}", id, userAccount);
if (userAccount.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, userAccount.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!userAccountRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
Optional<UserAccount> result = userAccountRepository
.findById(userAccount.getId())
.map(existingUserAccount -> {
if (userAccount.getName() != null) {
existingUserAccount.setName(userAccount.getName());
}
return existingUserAccount;
})
.map(userAccountRepository::save);
return ResponseUtil.wrapOrNotFound(
result,
HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, userAccount.getId().toString())
);
}
/**
* {@code GET /user-accounts} : get all the userAccounts.
*
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of userAccounts in body.
*/
@GetMapping("")
public List<UserAccount> getAllUserAccounts(
@RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
) {
LOG.debug("REST request to get all UserAccounts");
if (eagerload) {
return userAccountRepository.findAllWithEagerRelationships();
} else {
return userAccountRepository.findAll();
}
}
/**
* {@code GET /user-accounts/:id} : get the "id" userAccount.
*
* @param id the id of the userAccount to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the userAccount, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
public ResponseEntity<UserAccount> getUserAccount(@PathVariable("id") Long id) {
LOG.debug("REST request to get UserAccount : {}", id);
Optional<UserAccount> userAccount = userAccountRepository.findOneWithEagerRelationships(id);
return ResponseUtil.wrapOrNotFound(userAccount);
}
/**
* {@code DELETE /user-accounts/:id} : delete the "id" userAccount.
*
* @param id the id of the userAccount to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUserAccount(@PathVariable("id") Long id) {
LOG.debug("REST request to delete UserAccount : {}", id);
userAccountRepository.deleteById(id);
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
.build();
}
}