I have an existing Table in SQL Server.
CREATE TABLE [dbo].[STUDENTS](
[ID] [int] NOT NULL,
[FIRSTNAME] [varchar](50) NOT NULL,
[LASTNAME] [varchar](50) NOT NULL,
[EMAIL] [varchar](100) NOT NULL,
[AGE] [int] NOT NULL,
[ADDRESS] [varchar](3000) NOT NULL,
PRIMARY KEY (ID)
);
I have created this entity in JAVA to me able to extract data using Hibernate.
package com.My_task_be.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTS")
public class Student {
#Id
#Column(name = "ID")
public int id;
#Column(name = "FISRTNAME")
public String firstName;
#Column(name = "LASTNAME")
public String lastName;
#Column(name = "EMAIL")
public String email;
#Column(name = "AGE")
public int Age;
#Column(name = "ADDRESS")
public String Address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
This is the repository
#Repository
public interface StudentRepository extends CrudRepository<Student, Integer>{
List<Student> findAll();
}
This is the controller
#RestController
public class AppController {
#Autowired
private StudentRepository studentRpository;
#GetMapping("/getAllStudents")
public List<Student> getAllStudents(){
return studentRpository.findAll();
}
#GetMapping("/helloWorld")
public String helloWorld(){
return "Hello World!";
}
}
When i run http://localhost:8080/getAllStudents
I get Invalid column name 'fisrtname'.
I dont want hibernate to create a new table I just want it to read from an existing table.
And I have specified the Column names but still it did not work.
Any ideas?
You have a typo in FISRTNAME. It is FIRSTNAME, change as below
#Column(name = "FIRSTNAME")
public String firstName;
Related
I am trying to find a specific object. I'm using the following code, but it seem like get only sends back a Boolean that verifies that there is a key with this name, but not an array of Boolean values that I need to use in my program:
private Map<User, ArrayList<Boolean>> userDayOfVacationMap;
public ArrayList<Boolean> getUserVacationList(User key){
return this.userDayOfVacationMap.get(key);
}
Is there a method for this?
Here is the User object:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
#OneToMany(mappedBy="user", cascade = CascadeType.ALL)
public Set<Vacation> vacations;
public User(String firstName, String lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
public User(){}
public Set<Vacation> getVacations() {
return vacations;
}
public void setId(int id){
this.id = id;
}
public Integer getId(){
return this.id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
However, I can't add a variable in this function, because it would add non-useful information into my database.
i have a MySQL database which is updated from Java with Entities.
I need a join table between two tables which contains 3 columns.
1 column from table Bar ("bar_id")
2 columns from table Owner ("owner_id", "bought")
Could you please tell me if that is possible or how I could realize that.
I want a join table which looks like this:
'bar_id' | 'owner_id' | 'bought'
--------------------------------
BaseEntity.java
#MappedSuperclass
public class BaseEntity {
private int id;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId(){ return this.id; }
public void setId(int id){ this.id = id; }
}
Bar.java
#Entity
#Table(name="bar")
public class Bar extends BaseEntity{
private String name;
private String bought;
private List<Fan> fan;
private List<Owner> owner;
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="bought")
public String getBought() {
return bought;
}
public void setBought(String bought) {
this.bought = bought;
}
#ManyToMany(mappedBy="bar", targetEntity=Owner.class)
public List<Owner> getOwner() {
return owner;
}
public void setOwner(List<Owner> owner) {
this.owner = owner;
}
#ManyToMany
#JoinColumn(name="fan")
public List<Fan> getFan() {
return fan;
}
public void setFan(List<Fan> fan) {
this.fan = fan;
}
}
Owner.java
#Entity
#Table(name="owner")
public class Owner extends BaseEntity{
private String firstname;
private String lastname;
private String birthday;
private java.sql.Date bought;
private List<Bar> bar;
#Column(name="firstname")
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name="lastname")
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name="birthday")
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
#Column(name="bought")
public java.sql.Date getBought() {
return bought;
}
public void setBought(java.sql.Date bought) {
this.bought = bought;
}
#ManyToMany
#JoinColumn(name="bar")
public List<Bar> getBar() {
return bar;
}
public void setBar(List<Bar> bar) {
this.bar = bar;
}
}
You can create a Join table by the using #JoinTable annotation.
Please have a look at this post which explains how to achieve it.
How to create join table with JPA annotations?
I have two tables as below in my mysql db:
CREATE TABLE if not exists USER (
profile_id int(15) NOT NULL AUTO_INCREMENT,
user_id varchar(30) NOT NULL,
password varchar(30) NOT NULL,
first_name varchar(50) NOT NULL,
last_name varchar(50) NOT NULL,
gender char(1) NOT NULL,
nationality varchar(30) NOT NULL,
date_of_birth date NOT NULL,
place_of_birth varchar(30) DEFAULT NULL,
notes tinytext,
PRIMARY KEY (profile_id),
KEY last_name_ind (last_name)
) ENGINE=InnoDB;
CREATE TABLE if not exists USER_CONTACT (
contact_id int(5) NOT NULL AUTO_INCREMENT,
profile_id int(15) NOT NULL,
email_id varchar(30) NOT NULL,
phone_no varchar(15) NOT NULL,
address_current varchar(50) DEFAULT NULL,
address_work varchar(50) DEFAULT NULL,
address_permanent varchar(50) DEFAULT NULL,
alternate_email varchar(30) DEFAULT NULL,
alternate_phone varchar(30) DEFAULT NULL,
PRIMARY KEY (contact_id),
KEY A2B_USER_BASIC_FK (profile_id),
CONSTRAINT A2B_USER_FK FOREIGN KEY (profile_id) REFERENCES a2b_user_basic (profile_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
Then I want to save the user and user contact details together using JPA. The problem I am facing is storing the profile_id of table User to the second table USER_CONTACT as foreign key. This save should happen along with the user save.
Here are my entity classes.
User.java corresponds to the user table and I want to save the User using JPA. upon saving user contact entry.
//User.java
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name="USER")
public class User extends BaseEntity{
#Column(name="profile_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer profileId;
#Column(name="user_id")
#NotEmpty
protected String userId;
#Column(name="password")
protected String password;
#Column(name="first_name")
#NotEmpty
protected String firstName;
#Column(name="last_name")
#NotEmpty
protected String lastName;
#Column(name="gender")
#NotEmpty
protected String gender;
#Column(name="nationality")
#NotEmpty
protected String nationality;
#Column(name="date_of_birth")
protected Date dateOfBirth;
#Column(name="place_of_birth")
protected String placeOfBirth;
#Column(name="notes")
protected String notes;
#OneToOne(mappedBy="user",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinColumn(name = "profile_id")
protected UserContact userContact;
public Integer getProfileId() {
return profileId;
}
public void setProfileId(Integer profileId) {
this.profileId = profileId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPlaceOfBirth() {
return placeOfBirth;
}
public void setPlaceOfBirth(String placeOfBirth) {
this.placeOfBirth = placeOfBirth;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public UserContact getUserContact() {
return userContact;
}
public void setUserContact(UserContact userContact) {
this.userContact = userContact;
}
}
UserContact.java corresponds to the USER_CONTACT table and I want to establish a one to one relationship.
// UserContact.java
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
import com.a2b.trackz.framework.model.BaseEntity;
#Entity
#Table(name="USER_CONTACT")
public class UserContact extends BaseEntity {
#Column(name="contact_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer contactId;
#Column(name="profile_id")
protected Integer profileId;
#Column(name="email_id")
#NotEmpty
protected String emailId;
#Column(name="phone_no")
#NotEmpty
protected String phoneNo;
#Column(name="address_current")
protected String addressCurrent;
#Column(name="address_work")
protected String addressWork;
#Column(name="address_permanent")
protected String addressPermanent;
#Column(name="alternate_email")
protected String alternateEmail;
#Column(name="alternate_phone")
protected String alternatePhone;
#OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
protected User user;
public Integer getContactId() {
return contactId;
}
public void setContactId(Integer contactId) {
this.contactId = contactId;
}
public Integer getProfileId() {
return profileId;
}
public void setProfileId(Integer profileId) {
this.profileId = profileId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getAddressCurrent() {
return addressCurrent;
}
public void setAddressCurrent(String addressCurrent) {
this.addressCurrent = addressCurrent;
}
public String getAddressWork() {
return addressWork;
}
public void setAddressWork(String addressWork) {
this.addressWork = addressWork;
}
public String getAddressPermanent() {
return addressPermanent;
}
public void setAddressPermanent(String addressPermanent) {
this.addressPermanent = addressPermanent;
}
public String getAlternateEmail() {
return alternateEmail;
}
public void setAlternateEmail(String alternateEmail) {
this.alternateEmail = alternateEmail;
}
public String getAlternatePhone() {
return alternatePhone;
}
public void setAlternatePhone(String alternatePhone) {
this.alternatePhone = alternatePhone;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
this.profileId=user.getProfileId();
}
}
Change your entity classes reference like below:
User.Java
#OneToOne(mappedBy="user",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
protected UserContact userContact;
UserContact.java
//remove this
#Column(name="profile_id")
protected Integer profileId;
#OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
protected User user;
//add this
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "profile_id", nullable = false)
protected User user;
I am using Spring boot and trying to implement many to many relationship between User and Skill. I have a table users_skills with columns user_id and skill_id. I keep getting "JoinColumn cannot be resolved to a type" error in #JoinColumn annotations in STS when trying to implement the relationship. Below is my User class
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String email;
private String firstName;
private String lastName;
private List<Skill> skills = new ArrayList<Skill>();
protected User() {}
public User(String email,String firstName, String lastName) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id ;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email ;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName ;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName ;
}
#ManyToMany
#JoinTable(name="users_skills",
joinColumns={#JoinColumn(name="user_id")},
inverseJoinColumns={#JoinColumn(name="skill_id")})
public List<Skill> getSkills(){
return skills;
}
public void setSkills(List<Skill> skills) {
this.skills = skills ;
}
}
Just write this at the head of your class
import javax.persistence.JoinColumn;
Sometime eclipse doesn't show the link to import it in context menu, but it's there. Hope it will help someone.
I am beginner on Hibernate.
I am getting this error message and could not figure out what is wrong:
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: com.hibernate.aris.Subscribers column: city (should be mapped with insert="false" update="false")"
I read somewhere that one has to set the property within the HBM file to "inverse" but I don't really know what that means yet.
Any advice would be appreciated?
Embeddable Class called Address
#Embeddable
public class Address {
#Column (name = "STREET_NAME")
private String street;
#Column (name = "CITY_NAME")
private String city;
#Column (name = "POST_CODE")
private String postcode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
Subscribers Class
#Entity
#Table(name = "Subscriberstbl")
public class Subscribers {
private int subID;
private String firstname;
private String lastname;
#Embedded
#AttributeOverrides({
#AttributeOverride(name ="street", column = #Column(name="HOME_STREET_NAME")),
#AttributeOverride(name = "city", column = #Column(name="HOME_CITY_NAME")),
#AttributeOverride(name = "postcode", column = #Column(name="HOME_POST_CODE"))})
private Address homeaddress;
#Embedded
private Address officeaddress;
//Getters and Setters
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Id
#GeneratedValue
public int getSubID() {
return subID;
}
public void setSubID(int subID) {
this.subID = subID;
}
public Address getOfficeAddress() {
return officeaddress;
}
public void setOfficeAddress(Address address) {
this.officeaddress = address;
}
public Address getHomeaddress() {
return homeaddress;
}
public void setHomeaddress(Address homeaddress) {
this.homeaddress = homeaddress;
}
}
You are mixing access by FIELD (annotation on field) and by PROPERTY (annotation on accessorss) and PROPERTY is the winner so #AttributesOverride is ignored.
Try move #Id #GeneratedValue from accessor to field class.