Entity Exercise Master
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
#EnableAutoConfiguration
#Entity
#Table(name = "exercise_master")
public class Exercise_Master {
private static final long serialVersionUID =1L;
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name="Ex_id")
private Integer Ex_id;
#Column(name="Problem_statement")
private String prob_statement;
#OneToMany(cascade=CascadeType.ALL, targetEntity = Vm_Master.class)
#JoinColumn(name="fk_Ex_id",referencedColumnName="Ex_id")
private List<Vm_Master> vm_master;
public Integer getEx_id() {
return Ex_id;
}
public void setEx_id(Integer ex_id) {
Ex_id = ex_id;
}
public String getProb_statement() {
return prob_statement;
}
public void setProb_statement(String prob_statement) {
this.prob_statement = prob_statement;
}
public List<Vm_Master> getVm_master() {
return vm_master;
}
public void setVm_master(List<Vm_Master> vm_master) {
this.vm_master = vm_master;
}
}
another entity Vm_master
import org.springframework.transaction.annotation.Transactional;
#Entity
#Transactional
#Table(name="vm_master")
public class Vm_Master {
private static final long serialVersionUID =1L;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="vm_id")
private Long Vm_id;
#Column
private String Vm_uuid;
#Column
private String Vm_name;
#ManyToOne
#JoinColumn(name="fk_Ex_id")
private Exercise_Master exercise_master;
public Long getVm_id() {
return Vm_id;
}
public void setVm_id(Long vm_id) {
Vm_id = vm_id;
}
public String getVm_uuid() {
return Vm_uuid;
}
public void setVm_uuid(String vm_uuid) {
Vm_uuid = vm_uuid;
}
public String getVm_name() {
return Vm_name;
}
public void setVm_name(String vm_name) {
Vm_name = vm_name;
}
public Exercise_Master getExercise_master() {
return exercise_master;
}
public void setExercise_master(Exercise_Master exercise_master) {
this.exercise_master = exercise_master;
}
}
Repository of both entity
public interface Exercise_MasterRepo extends JpaRepository<Exercise_Master,Long>{
}
//
public interface Vm_MasterRepo extends JpaRepository<Vm_Master, Long>{
}
Controller
#PostMapping("/saveExercise")
public String saveExercise(#ModelAttribute Exercise_Master ex,#ModelAttribute Vm_Master vm)
{
exer_repo.save(ex);
vm_repo.save(vm);
return "redirect:/AddExercise";
}
HTML Page
<form th:action="#{/saveExercise}" th:object="${ex}" method="POST">
<div class="form-group">
<label for="prob_statement">Problem Statement :</label>
<textarea class="form-control" id="prob_statement" name="prob_statement" rows="2" required ></textarea><br>
<label for="Vm_name">Vm_name:</label>
<textarea class="form-control" id="Vm_name" name="Vm_name" required ></textarea><br>
<label for="Vm_uuid">Vm_uuid:</label>
<textarea class="form-control" id="Vm_uuid" name="Vm_uuid" required ></textarea><br>
<button type="submit" id="submit" class="btn btn-primary">Save</button>
</div>
</form>
while inserting the of all field in html page value foreign key of vm_master which is mapped to primary key of Exercise_master is not getting the value.
all the other value are getting store in the database.
Exercise_master
Vm_master
You are not setting anything to the exercise_master field in the Vm_master entity. There's no way for vm_master to know that you are trying to map the exercise master with it. You'll need to set exercise_master field in the Vm_master object before saving the vm_master. Try doing something like this
#PostMapping("/saveExercise")
public String saveExercise(#ModelAttribute Exercise_Master ex,#ModelAttribute Vm_Master vm)
{
exer_repo.save(ex);
vm.setExercise_master(ex);
vm_repo.save(vm);
return "redirect:/AddExercise";
}
Let me know if this helps.
Related
I connected my bat to the database.
I mapped it to view the contents in HTML,
but typing url(/index) in the address bar, I can only see the contents of the table.
What is the problem?
public class Controller {
#Autowired
noticeService ns;
#RequestMapping(value="/index", method = RequestMethod.GET)
public ModelAndView index (HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
List<noticeModel>noticeList = ns.getNotice();
mav.addObject("noticeList", noticeList);
mav.setViewName("index"); // HTML ADDRESS
return mav;
}
}
#Builder #Data
public class noticeModel {
private int notice_id;
private String notice_tilte;
private String notice_name;
private Date notice_created_date;
private Date notice_revised_date;
private String notice_text;
private String notice_pw;
}
#Service
public class noticeService {
#Autowired
public noticeMapper mapper;
public List<noticeModel> getNotice() {
return mapper.getNotice();
}
}
#Repository
#Mapper
public interface noticeMapper {
List<noticeModel> getNotice();
}
I'm trying to display data from a database in a spring application.
<div class="container-fluid">
<h1>Welcome</h1>
<p>Some text</p>
</div>
<ul>
<!--/#thymesVar id="film" type="java.util.List<com.example.project1.accessToData.model.Film>"/-->
<li th:each ="film:${film}">
<span th:text="${film}"></span>
</li>
</ul>
public FilmIndexControler(FilmService filmService) {
this.filmService = filmService;
}
#GetMapping
String showFilms(Model model){
Iterable<Film> film = filmService.findAll();
model.addAttribute("film",film);
return "index";
}
public class Film {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotEmpty(message="Cant be empty")
private String title;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate productionYear;
private String descryption;
#NotEmpty (message="Cant be empty")
private String link}
public Iterable<Film> findAll () {
return this.filmRepository.findAll();
}
When I try to display it on the site, nothing related to the spring happens. I can't see films in html.
#RestController
#RequestMapping("/api/film")
public class FilmApi {
private static final Logger logger = LoggerFactory.getLogger(FilmApi.class);
private final FilmManager filmManager;
#Autowired
public FilmApi(final FilmManager filmManager) {
this.filmManager = filmManager;
}
#GetMapping(value = "/lista",params = {"!sort", "!page", "!size"} )
public ResponseEntity<Iterable<Film>> getAll(){
logger.warn("Lista filmów");
return ResponseEntity.ok(this.filmManager.findAll());
}
#GetMapping
public ResponseEntity<List<Film>> findFilm(#Param("title") String title){
return ResponseEntity.ok(this.filmManager.findFilm(title));
}
#PostMapping
public ResponseEntity<Film> addFilm(#RequestBody Film film){
this.filmManager.save(film);
return ResponseEntity.noContent().build();
}
#PutMapping("/{id}")
public ResponseEntity<?> updateFilm(#PathVariable Long id,#RequestBody Film film){
if (!this.filmManager.exist(id)){
return ResponseEntity.notFound().build();
}
film.setId(id);
this.filmManager.save(film);
return ResponseEntity.noContent().build();
}
#DeleteMapping
public void deleteFilm(#RequestParam Long index){
if (!this.filmManager.exist(index)){
ResponseEntity.notFound().build();
}
this.filmManager.deleteById(index);
ResponseEntity.noContent().build();
}
}
Ok I added api controller. When I enter localhostapi:8080/api/film/lista, all data is displayed If you need anything else, I will add it soon.
change variable name from film to films in controller:
model.addAttribute("films",film);
and in html file :
<li th:each ="film: ${films}">
I have already connected my springboot to MySQL database. I want to display the username when user_id is specified in the HTTP request. e.g. http://8080/user/1 must display the name of the user with user_id 1.
The table contains attributes as:
| Integer user_id; | String username; | String fathername; | String mothername;
I have already tried this code in by Controller class but i does not seem to be working
#RequestMapping("/{userid}")
#ResponseBody
public String getById(Integer userid) {
String name="";
try {
Optional<Persondetails> persondetails=persondetailsRepository.findById(personid);
name = String.valueOf(userdetails.getName());
}
catch (Exception ex) {
return "Name not found";
}
return "The Name of the user is : " + name;
}
my repository code:
import java.util.List;
import java.util.Optional;
public interface UserdetailsRepository extends JpaRepository<Userdetails, Integer> {
public Optional<Userdetails> findById(Integer userid);
}
It says getName() is undefined for the type Optional
But i have defined it in Userdetails class
public class Userdetails {
#Id
#GeneratedValue
#Column(name="user_id")
private Integer userid;
#Column(name="name")
private String name;
#Column (name="fathers_name")
private String fathersname;
#Column(name="mothers_name")
private String mothersname;
public Userdetails() {
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getFathersname() {
return fathersname;
}
public void setFathersname(String fathersname) {
this.fathersname = fathersname;
}
public void setMothersname(String mothersname) {
this.mothersname = mothersname;
}
public String getMothersname() {
return mothersname;
}
}
It's missing the method type GET, you can do by two options:
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User findOne(#PathVariable("id") int id){
return userService.findById(id);
}
OR
#GetMapping("/{id}")
public String getString(#PathVariable("id") int id) {
return "Helloworld";
}
Spring boot Connect with Mysql and get Data.
application.properties
server.contextPath=/demo-user
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
*Controller.Java
#RequestMapping({"/users"})
public class UserController {
#Autowired
private UserService userService;
#GetMapping(path = {"/{id}"})
public User findOne(#PathVariable("id") int id){
return userService.findById(id);
}
}
UserService.java
public interface UserService {
User findById(int id);
}
UserServiceImpl.java
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository repository;
#Override
public User findById(int id) {
return repository.findOne(id);
}
}
UserRepository .java
public interface UserRepository extends Repository<User, Integer> {
User findOne(int id);
}
User.java
#Entity
#Table(name = "user")
public class User {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
//setter and getter
}
Make request from browser or application.
http://localhost:8080/demo-user/users/1
I'm new to Spring Boot. I have a mysql database, I use a query to count row in my table. But it's not work, it still return my original table data. Can you help me check my code.
Here is my Entity:
#Entity
#Table(name = "act_id_membership", schema = "activiti", catalog = "")
#IdClass(ActIdMembershipEntityPK.class)
public class ActIdMembershipEntity {
private String userId;
private String groupId;
#Id
#Column(name = "USER_ID_")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Id
#Column(name = "GROUP_ID_")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActIdMembershipEntity that = (ActIdMembershipEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
Here is my query:
#Repository
public interface MemershipRepository extends JpaRepository<ActIdMembershipEntity, String> {
#Query ("select new com.example.activiti_restful.dtos.UserMembership(i.userId, count(i)) from ActIdMembershipEntity i where i.userId ='kermit'")
UserMembership countMemberships(String userId);
}
Updated code:
My service class:
#Service
public class MembershipService {
#Autowired
private MemershipRepository repository;
public long count() {
return repository.count();
}
My resource class:
#RestController
public class MembershipResource {
#Autowired
private MembershipService membershipService;
#GetMapping("/membership")
public long list() {return membershipService.count();}
}
My custom JSON Object class:
public class UserMembership {
private String userId;
private long numberOfusers;
public UserMembership(String userId, long numberOfusers) {
this.userId = userId;
this.numberOfusers = numberOfusers;
}
}
MySQL Table:
act_id_membership
According repositories documentation using CrudRepository provides a method called count() that is one of the Superinterfaces which JpaRepository is implemented.
Based CrudRepository documentation says:
long count(); Returns the number of entities.
Then you should use CrudRepository method. In addition Remove Uppercase MembershipREPOSITORY, by java code convention, you have to use by following way MembershipRepository.
#Repository
public interface MembershipRepository extends JpaRepository <ActIdMembershipEntity, String> {
}
And use it in your Service:
#Service
public class MembershipService {
#Autowired
private MembershipRepository repo;
public long count() {
return repo.count();
}
}
UPDATED
Based on your requirement:
In Controller:
#RestController
public class MembershipResource {
#Autowired
private MembershipService membershipService;
#GetMapping("/membership")
public List<Object> list() { return membershipService.countMemberships();
}
}
In Service:
#Service
public class MembershipService {
#Autowired
private MemershipRepository repository;
public List<Object> countMemberships() {
return repository.countMemberships();
}
}
In Repository:
#Repository
public interface MemershipRepository extends JpaRepository<ActIdMembershipEntity, String> {
#Query ("select i.userId, count(i) from ActIdMembershipEntity i where i.userId ='kermit'")
List<Object> countMemberships();
}
*> Actually I want it return a json format like [{ name: kermit, value:6}]. Now it just return a number 6 only. How I can do that? Thank you!
First, create a class to wrap your data:
public class UserMembership {
private String userId;
private long numberOfUsers;
public UserMembership(String userId, long numberOfUsers) {
this.userId = userId;
this.numerOfUsers = numberOfUsers;
}
}
Then
#Repository
public interface MembershipRepository extends JpaRepository <ActIdMembershipEntity, String> {
#Query ("select new *****.UserMembership(i.userId, count(i)) from ActIdMembershipEntity i where i.userId = :userId")
UserMembership countMemberships(String userId);
}
*****: your full package name
Hope it help!
I used Eclipselink MOXy to convert my POJO(using JPA) to json. and it's work.
but i have one problem. I have pojo class MAccount contain many to one relation to class MProduct,. when I convert to json, result show that class MAccount not in class MProduct.
here my class MAccount implementation:
#XmlRootElement
#Entity
#Table(name="m_account")
public class MAccount extends BaseObject implements Serializable {
private static final long serialVersionUID = UUID.randomUUID().getMostSignificantBits();
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#XmlID
private Long id;
#Column(name="account_id")
private String accountId;
#Column(name="card_number")
private String cardNumber;
//bi-directional many-to-one association to Product
#ManyToOne
#JoinColumn(name="m_product_id")
#XmlIDREF
private MProduct mProduct;
public MCustomerAccount() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountId() {
return this.accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public MProduct getMProduct() {
return this.mProduct;
}
public void setMProduct(MProduct mProduct) {
this.mProduct = mProduct;
}
// Imlement base object method
...
}
here my class MProduct implementation:
#XmlRootElement
#Entity
#Table(name="m_product")
public class MProduct extends BaseObject implements Serializable {
private static final long serialVersionUID = UUID.randomUUID().getMostSignificantBits();
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#XmlID
private Long id;
#Column(name="product_code")
private String productCode;
#Column(name="product_name")
private String productName;
//bi-directional many-to-one association to MAccount
#OneToMany(mappedBy="mProduct")
#XmlInverseReference(mappedBy="mProduct")
private Set<MAccount> mAccountList;
public MProduct() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Set<MAccount> getMAccountList() {
return this.mAccountList;
}
public void setMAccountList(Set<MAccount> mAccountList) {
this.mAccountList = mAccountList;
}
// Imlement base object method
...
}
And generate JSON from MAccount class
{"MAccount":[
{"#type":"mAccount","id":"6","accountId":"05866039901"},
{"#type":"mAccount","id":"7","accountId":"25600036290"}]
}
there is no MProduct in there, the correct json result should be like below
{"MAccount":[
{"#type":"mAccount","id":6,"accountId":"05866039901","MProduct":{"#type":"mProduct","productCode":"T01","productName":"Book"}},
{"#type":"mAccount","id":7,"accountId":"25600036290","MProduct":{"#type":"mProduct","productCode":"T02","productName":"Pen"}}]
}
Is Anyone know how to solve this problem
Thank's b4
Because you are annotating the field, there is a chance that JPA has not populated that field yet due to lazy loading. If you annotate the property (get/set) instead do you still see this behaviour?
For more information on #XmlInverseReference see:
http://bdoughan.blogspot.com/2010/07/jpa-entities-to-xml-bidirectional.html