Новичок
Профиль
Группа: Участник
Сообщений: 6
Регистрация: 25.3.2018
Репутация: нет Всего: нет
|
Добрый вечер. У меня есть вопрос он наверное глупый но я все таки его напишу. Как мне запрос на вывод данных с одной таблицы в другую в еклипсе. БД MySQL У меня есть пару таблиц, но мне нужно для начала понять сделать хотя бы с двумя. Таблицы связаны в Еклипсе. Есть таблица 1-я в которую я хочу вывести данные с 2-й таблицы Есть поля в Двух таблицах "Тип номера" Мне нужно с 2-й таблицы вывести данные в 1-ю таблицу в это поле. Не знаю как это реализовать. И куда поместить. Я смотрел в интернете, но ничего не нашел, может плохо искал. Если кто-то такое делал(надеюсь делали) обьясните новичку что к чему буду благодарен. Могу скинуть сюда код что есть может так будет легче чтобы я понял что нужно дописать, добавить. Спасибо что выслушали. App Contoller Код | package com.honchar.springmvc.controller; import java.util.List; import java.util.Locale; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.honchar.springmvc.model.Guests; import com.honchar.springmvc.service.GuestsService1; @Controller @RequestMapping("/") public class AppController { @Autowired GuestsService1 service; @Autowired MessageSource messageSource; @RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET) public String listGuests(ModelMap model) { List<Guests> guests = service.findAllGuests(); model.addAttribute("guests", guests); return "allguestss"; } @RequestMapping(value = {"/new" }, method = RequestMethod.GET) public String newGuests(ModelMap model) { Guests guests = new Guests(); model.addAttribute("guests", guests); model.addAttribute("edit", false); return "registration"; } @RequestMapping(value = { "/new" }, method = RequestMethod.POST) public String saveGuests(@Valid Guests guests, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "registration"; } if(!service.isGuestsIdUinque(guests.getId())) { FieldError idError = new FieldError("guests","id", messageSource.getMessage("non.uique.id", new Integer[] {guests.getId()}, Locale.getDefault())); result.addError(idError); return "registration"; } service.saveGuests(guests); model.addAttribute("success", "Guests " + guests.getName() + " registered successfully"); return "success"; } @RequestMapping(value = { "/edit-{id}-guests" }, method = RequestMethod.GET) public String editGuests(@PathVariable int id, ModelMap model) { Guests guests = service.findGuestsById(id); model.addAttribute("guests", guests); model.addAttribute("edit", true); return "registration"; } @RequestMapping(value = { "/edit-{id}-guests" }, method = RequestMethod.POST) public String updateGuests(@Valid Guests guests, BindingResult result, ModelMap model, @PathVariable int id) { if (result.hasErrors()) { return "registration"; } if(!service.isGuestsIdUinque(guests.getId())) { FieldError idError = new FieldError("guests","id", messageSource.getMessage("non.uique.id", new Integer[] {guests.getId()}, Locale.getDefault())); result.addError(idError); return "registration"; } service.updateGuests(guests); model.addAttribute("success", "Guests " + guests.getName() + " update successfully"); return "success"; } @RequestMapping(value = { "/delete-{id}-guests"}, method = RequestMethod.GET) public String deleteGuests(@PathVariable int id) { service.deleteGuestsById(id); return "redirect:/list"; } }
|
AbstractDao Код | package com.honchar.springmvc.dao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; public abstract class AbstractDao<PK extends Serializable, T> { private final Class<T> persistentClass; @SuppressWarnings("unchecked") public AbstractDao(){ this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; } @Autowired private SessionFactory sessionFactory; protected Session getSession(){ return sessionFactory.getCurrentSession(); } @SuppressWarnings("unchecked") public T getByKey(PK key) { return (T) getSession().get(persistentClass, key); } public void persist(T entity) { getSession().persist(entity); } public void delete(T entity) { getSession().delete(entity); } protected Criteria createEntityCriteria(){ return getSession().createCriteria(persistentClass); } }
|
GuestsDao1 Код | package com.honchar.springmvc.dao; import java.util.List; import com.honchar.springmvc.model.Guests; public interface GuestsDao1 { Guests findById (int id); void saveGuests(Guests guests); void deleteGuestsById(int id); List<Guests> findAllGuests(); Guests findGuestsById(int id); }
|
GuestsDaoImpl Код | package com.honchar.springmvc.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import com.honchar.springmvc.model.*; @Repository("guestsDao1") public class GuestsDaoImpl1 extends AbstractDao<Integer, Guests> implements GuestsDao1 { public Guests findById (int id) { return getByKey(id); } public void saveGuests(Guests guests) { persist(guests); } public void deleteGuestsById(int id) { Query query = getSession().createSQLQuery("delete from Guests where id = :id"); query.setInteger("id", id); query.executeUpdate(); } @SuppressWarnings("unchecked") public List<Guests> findAllGuests() { Criteria criteria = createEntityCriteria(); return (List<Guests>) criteria.list(); } public Guests findGuestsById(int id) { Criteria criteria = createEntityCriteria(); criteria.add(Restrictions.eq("id", id)); return (Guests) criteria.uniqueResult(); } }
|
Таблица Guests в которою я хочу внести данные Код | package com.honchar.springmvc.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="GUESTS") public class Guests implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "SURNAME") private String surname; @Size(min=3, max=50) @Column(name = "NAME") private String name; @Column(name = "TYPE_ROOMS") private String type_rooms; @Column(name = "NUMBER_ROOM") private int number_room; @Column(name = "ADDITIONAL_SERVICE") private String additional_Service; @Column(name = "SPENDING_TYPES") private String spending_Types; @Column(name = "NUMBER_PHONE") private int number_phone; @Column(name = "PAYMENT") private String payment; @Column(name = "TYPE_CARDS") private String type_cards; @Column(name = "NUMBER_CARDS") private int number_cards; @NotNull @Digits(integer=8, fraction=2) @Column(name = "AMOUNT_PAYMENT", nullable = false) private BigDecimal amount_payment; @Temporal(TemporalType.DATE) @DateTimeFormat(pattern="dd/MM/yyyy") @Column(name = "DATE" ) private Date date; @OneToMany(mappedBy="guests", cascade = CascadeType.ALL) private List<types_of_rooms> type_of_rooms; @OneToMany(mappedBy="guests", cascade = CascadeType.ALL) private List<type_of_payment> type_payment; @OneToMany(mappedBy="guests", cascade = CascadeType.ALL) private List<type_of_cards> types_cards; @OneToMany(mappedBy="guests", cascade = CascadeType.ALL) private List<spending_types> types_spending; @OneToMany(mappedBy="guests", cascade = CascadeType.ALL) private List<additional_services> add_services; public Guests() { } public Guests(String surname, String name, String type_rooms, int number_room, String additional_Service, String spending_Types, int number_phone,String payment,String type_cards, int number_cards, BigDecimal amount_payment, Date date) { this.surname = surname; this.name = name; this.type_rooms = type_rooms; this.number_room = number_room; this.additional_Service = additional_Service; this.spending_Types = spending_Types; this.number_phone = number_phone; this.payment = payment; this.type_cards = type_cards; this.number_cards = number_cards; this.amount_payment = amount_payment; this.date = date; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType_rooms() { return type_rooms; } public void setType_rooms(String type_rooms) { this.type_rooms = type_rooms; } public int getNumber_room() { return number_room; } public void setNumber_room(int number_room) { this.number_room = number_room; } public String getAdditional_Service() { return additional_Service; } public void setAdditional_Service(String additional_Service) { this.additional_Service = additional_Service; } public String getSpending_Types() { return spending_Types; } public void setSpending_Types(String spending_Types) { this.spending_Types = spending_Types; } public int getNumber_phone() { return number_phone; } public void setNumber_phone(int number_phone) { this.number_phone = number_phone; } public String getPayment() { return payment; } public void setPayment(String payment) { this.payment = payment; } public String getType_cards() { return type_cards; } public void setType_cards(String type_cards) { this.type_cards = type_cards; } public int getNumber_cards() { return number_cards; } public void setNumber_cards(int number_cards) { this.number_cards = number_cards; } public BigDecimal getAmount_payment() { return amount_payment; } public void setAmount_payment(BigDecimal amount_payment) { this.amount_payment = amount_payment; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public List<types_of_rooms> getType_of_rooms() { return type_of_rooms; } public void setTypes_of_rooms(List<types_of_rooms> type_of_rooms) { this.type_of_rooms = type_of_rooms; } public List<type_of_payment> getType_payment() { return type_payment; } public void setType_payment(List<type_of_payment> type_payment) { this.type_payment = type_payment; } public List<type_of_cards> getTypes_cards() { return types_cards; } public void setTypes_cards(List<type_of_cards> types_cards) { this.types_cards = types_cards; } public List<spending_types> getTypes_spending() { return types_spending; } public void setTypes_spending(List<spending_types> types_spending) { this.types_spending = types_spending; } public List<additional_services> getAdd_services() { return add_services; } public void setAdd_service(List<additional_services> add_services) { this.add_services = add_services; } @Override public String toString(){ return "Guests [id=" + id +", surname=" + surname + ", name=" + name + ", type_rooms=" + type_rooms + ",additional_Service=" + additional_Service + ", spending_Types=" + spending_Types+ ", number_phone=" + number_phone +",payment=" + payment + ",type_cards=" + type_cards+ ",number_cards=" + number_cards +",amount_payment=" + amount_payment +", date=" + date + "]"; } }
|
Таблица types_of_rooms с которой данные хочу перенести в виде списка Код | package com.honchar.springmvc.model; import java.io.Serializable; import java.util.List; import javax.persistence.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; @Entity @Table(name = "TYPES_OF_ROOMS",catalog = "springmvc") public class types_of_rooms implements Serializable { @Id @GeneratedValue (strategy = GenerationType.AUTO) @Column(name = "ROOMS_ID") private long roomsId; @Column(name ="TYPE_ROOMS") private String type_rooms; @ManyToOne(optional = false) @JoinColumn(name = "TYPE_ROOMS", referencedColumnName = "TYPE_ROOMS", insertable = false, updatable = false) private Guests guests; public Guests getGuests () { return guests; } public void setGuests(Guests guests) { this.guests = guests; } public long getRoomsId() { return roomsId; } public void setRoomsId (long roomsId) { this.roomsId = roomsId; } public String getType_rooms() { return type_rooms; } public void setType_rooms(String type_rooms) { this.type_rooms = type_rooms; } @Override public String toString() { return "types_of_rooms [roomsId=" + roomsId + ", type_rooms = " + type_rooms +"]"; } }
|
GuestsService1 Код | package com.honchar.springmvc.service; import java.util.List; import com.honchar.springmvc.model.Guests; public interface GuestsService1 { Guests findById (int id); void saveGuests(Guests guests); void updateGuests(Guests guests); void deleteGuestsById(int id); List<Guests> findAllGuests(); Guests findGuestsById(int id); boolean isGuestsIdUinque(Integer id); }
|
GuestsServiceImpl1 Код | package com.honchar.springmvc.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.honchar.springmvc.dao.GuestsDao1; import com.honchar.springmvc.model.Guests; import com.honchar.springmvc.model.*; @Service("guestsService1") @Transactional public class GuestsServiceImpl1 implements GuestsService1 { @Autowired private GuestsDao1 dao; public Guests findById(int id) { return dao.findById(id); } public void saveGuests(Guests guests) { dao.saveGuests(guests); } public void updateGuests(Guests guests) { Guests entity = dao.findById(guests.getId()); if(entity!=null){ entity.setSurname(guests.getSurname()); entity.setName(guests.getName()); entity.setType_rooms(guests.getType_rooms()); entity.setNumber_room(guests.getNumber_room()); entity.setAdditional_Service(guests.getAdditional_Service()); entity.setSpending_Types(guests.getSpending_Types()); entity.setNumber_phone(guests.getNumber_phone()); entity.setPayment(guests.getPayment()); entity.setType_cards(guests.getType_cards()); entity.setNumber_cards(guests.getNumber_cards()); entity.setAmount_payment(guests.getAmount_payment()); entity.setDate(guests.getDate()); } } public void deleteGuestsById(int id) { dao.deleteGuestsById(id); } public List<Guests> findAllGuests() { return dao.findAllGuests(); } public Guests findGuestsById(int id) { return dao.findGuestsById(id); } public boolean isGuestsIdUinque(Integer id) { Guests guests = findGuestsById(id); return ( guests == null || ((id != null) && (guests.getId() == id))); } }
|
Присоединённый файл ( Кол-во скачиваний: 1 )
Mydatabases.rar 1,84 Kb
|