表关系参考的图像
从银行jsp页面提交后,由于新手的限制,从卡片jsp提交后全部在一张图片中
我也是stackoverflow的新手SPRING
。我试图用外键概念创建两个表。我已经关注了stackoverflow以及其他资源丰富的网站上的一些示例,并且管理创建了两个具有onetomany关系的表。但问题是,当我从卡片jsp页面提交时,我必须获取cart_id列下的第一行ID。相反,在从卡片jsp页面提交后,在bankadmin表下创建了新行,并且正在返回它的id。我很困惑,不知道如何纠正解决这个问题。请善待并指导我。而且我一直在搜索stackoverflow中的一周找不到任何帮助我的东西。提前谢谢。
@Entity
@Table(name = "bankAdmin")
public class bankAdmin implements Serializable{
@GeneratedValue(strategy=GenerationType.AUTO)
@Column (name = "bcode", nullable=false)
@Id private int bcode;
@Column (name = "bname")
private String bname;
@Column (name = "address")
private String address;
@Column (name = "phno")
private int phno;
@OneToMany(mappedBy="bankAdmin",cascade = CascadeType.ALL)
private Set<Cards> cards;
@Entity
@Table(name = "cards")
public class Cards implements Serializable {
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="cname", unique=true)
@Id private int cname;
@Column (name = "ctype")
private String ctype;
@Column (name = "min_sal")
private int min_sal;
@Column (name = "year_fee")
private int year_fee;
@Column (name = "rewards")
private String rewards;
@Column (name = "jperks")
private String jperks;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="cart_id", nullable=false)
private bankAdmin bankAdmin;
public Cards(){}
public Cards(String ctype, int min_sal, int year_fee, String rewards, String jperks, bankAdmin b){//int cname,
this.ctype=ctype;
this.min_sal=min_sal;
this.year_fee=year_fee;
this.jperks=jperks;
this.rewards=rewards;
this.bankAdmin=b;
}
public bankAdmin getBankAdmin() {
return bankAdmin;
}
public void setBankAdmin(bankAdmin bankAdmin) {
this.bankAdmin = bankAdmin;
}
public class CardsDaoImpl implements CardsDao{
@Autowired
SessionFactory sessionfactory;
public void save(Cards cards) {
Session session = null;
Transaction tx = null;
try
{
session = this.sessionfactory.openSession();
tx = session.beginTransaction();
bankAdmin bankadmin =new bankAdmin(); //=null;
String _ctype = cards.getctype();
int _min_sal = cards.getmin_sal();
int _year_fee = cards.getyear_fee();
String _rewards = cards.getrewards();
String _jperks = cards.getjperks();
Set<Cards> card = new HashSet<Cards>();
Cards config = new Cards(_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin);
card.add(config);
bankadmin.setcards(card);
// System.out.println("bankadmin: before " + bankadmin);
// bankadmin.setbname(bankadmin.getbname());// "SBI"
// bankadmin.setphno(bankadmin.getphno());//1234567890
// bankadmin.setaddress(bankadmin.getaddress());//Bengaluru
// System.out.println("bankadmin: after " + bankadmin);
// int _cname = cards.getcname();
// int bankadmin = bankadmin.getbcode();
//_cname,_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin
// card.add(config);
// config.setBankAdmin(cards.getBankAdmin(bankadmin));
// config.setcname(cards.getcname());
// config.setctype(cards.getctype());
// config.setmin_sal(cards.getmin_sal());
// config.setyear_fee(cards.getyear_fee());
// config.setrewards(cards.getrewards());
// config.setjperks(cards.getjperks());
// config.setBankAdmin(cards.getBankAdmin());
session.save(bankadmin);
session.save(config);
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
}
finally
{
session.close();
}
}
// get lms lights config from DB
public List<Cards> Ccards() {
Session session = null;
// Transaction tx = null;
List<Cards> Ccards = null;
try{
session = this.sessionfactory.openSession();
Ccards = session.createQuery("FROM Cards").list();
System.out.println("cards dao impl executed...");
System.out.println("cards config : "+ Ccards.toString());
}
catch (Exception e)
{
System.out.println("bankAdmin Dao impl Ex : " + e);
}
finally
{
session.close();
}
return Ccards;
}
}
BankDaoImpl
public class bankAdminDaoImpl implements bankAdminDao{
@Autowired
SessionFactory sessionfactory;
public void save(bankAdmin badmin) {
Session session = null;
Transaction tx = null;
try
{
session = this.sessionfactory.openSession();
tx = session.beginTransaction();
// bankAdmin bankadmin = new bankAdmin();
bankAdmin config = new bankAdmin();
config.setbcode(badmin.getbcode());
config.setbname(badmin.getbname());
config.setaddress(badmin.getaddress());
config.setphno(badmin.getphno());
session.save(config);//save//persist
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
}
finally
{
session.close();
}
}
// get lms lights config from DB
public List<bankAdmin> BbankAdmin() {
Session session = null;
// Transaction tx = null;
List<bankAdmin> BbankAdmin = null;
try{
session = this.sessionfactory.openSession();
BbankAdmin = session.createQuery("FROM bankAdmin").list();
System.out.println("bankAdmin dao impl executed...");
System.out.println("bankAdmin config : "+ BbankAdmin.toString());
}
catch (Exception e)
{
System.out.println("bankAdmin Dao impl Ex : " + e);
}
finally
{
session.close();
}
return BbankAdmin;
}
}
答案 0 :(得分:0)
好。我已经解决了你的问题。
首先,Spring框架很棒。该框架有很多功能,你应该利用它们。我不确定我是否能够涵盖这篇文章中的所有内容,所以请随时问我。
我创建了一个简单的Spring Boot应用程序。我总共收到了6个重要的文件,这些文件发布在下面。
请注意,我使用大写字母将您的类重命名为CamelCase。例如BankAdmin
。这被认为是编写java类的标准方法。另请注意,我将Cards
重命名为Card
,因此请记住在数据库中重命名您的表格。还记得将bankadmin表重命名为bank_admin。
您需要了解一些注释。 @Transactional
,@Autowired
和PersistenceContext
。
这是一个快速简单的解释。 @Transactional
为您管理所有事务,因此您不必开始和提交事务。 @Autowired
为您创建对象,因此您不必自己管理对象依赖项。 PersistenceContext
基本上为您创建了EntityManager并为您管理它。您不必创建会话也不必创建EntitManagerFactory。这三个注释的解释非常简短,所以你应该自己阅读它们。
我还删除了@Table(name = "bankAdmin")
和@Table(name = "cards")
。如果您遵循命名类和数据库表的标准方法,JPA可以自动查找这些表。它实际上很简单,但我仍然鼓励你自己调查一下。简而言之,资本来源变成小写,每个单词之间都以_
开头,以大写字母开头。即如果您的班级名称为BankAdmin
,则JPA会自动在您的数据库中查找名为bank_admin
的表。
application.properties - 有关您数据库的详细信息
spring.datasource.url=jdbc:mysql://localhost:3306/stackoverflow?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
以下代码仅用于测试功能
@SpringBootApplication
public class StackoverflowApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(StackoverflowApplication.class, args);
//Calling a class that is only made with the purpose of testing
Verification ts = ctx.getBean(Verification.class);
ts.run();
}
}
@Component
class Verification{
@Autowired
private BankAdminDao bad;
@Autowired
private CardsDao cd;
void run(){
//Create a new BankAdmin
BankAdmin ba = new BankAdmin();
ba.setAddress("someStreet");
ba.setPhno(12341234);
ba.setBname("myBanker");
//Create two cards and add them to a HashSet.
Card c1 = new Card("Visa", 1000, 1999, "Alot of", "Babes", ba);
Card c2 = new Card("Master Card", 2000, 500, "someThing", "anotherThing", ba);
Set<Card> cardList = new HashSet<>();
cardList.add(c1);
cardList.add(c2);
//Create a associatio between the BankAdmin and list of Cards
ba.setCards(cardList);
//Save them to the database.
bad.save(ba);
//Here we add a Card to an existing BankAdmin with the id 6 in the database.
//Create a new Card.
//The BankAdmin is set to null, because we not have not yet loaded the BankAdmin
Card c3 = new Card("Visa", 9999, 1337, "Alot of", "Male Babes", null);
//Save Card c3 with the BankAdmin id 6
cd.save(c3, 6);
}
}
<强> BankAdmin 强>
@Entity
public class BankAdmin implements Serializable{
@GeneratedValue(strategy=GenerationType.AUTO)
@Column (name = "bcode", nullable=false)
@Id private int bcode;
@Column (name = "bname")
private String bname;
@Column (name = "address")
private String address;
@Column (name = "phno")
private int phno;
@OneToMany(mappedBy="bankAdmin",cascade=CascadeType.ALL)
private Set<Card> cards;
//Getters and Setters have been removed to reduce the amount of code.
}
<强> BankAdminDao 强>
@Repository
//Transactional makes transaction automatical, so you do not have to begin and commit transactions yourself!
@Transactional
public class BankAdminDao{
//This makes your life a lot eaier!
//It will take care of your EntitManagerFactory and Sessions
@PersistenceContext
EntityManager em;
public void save(BankAdmin bank) {
em.merge(bank);
}
//get lms lights config from DB
public List<BankAdmin> getAllBankAdmin() {
List<BankAdmin> bankList = (List<BankAdmin>)em.createQuery("SELECT b FROM BankAdmin b");
return bankList;
}
public BankAdmin getBankAdmin(int bankId) {
return em.find(BankAdmin.class, bankId);
}
}
<强>卡强>
@Entity
public class Card implements Serializable {
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="cname", unique=true)
@Id private int cname;
@Column (name = "ctype")
private String ctype;
@Column (name = "min_sal")
private int min_sal;
@Column (name = "year_fee")
private int year_fee;
@Column (name = "rewards")
private String rewards;
@Column (name = "jperks")
private String jperks;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="cart_id", nullable=false)
private BankAdmin bankAdmin;
public Card(){}
public Card(String ctype, int min_sal, int year_fee, String rewards, String jperks, BankAdmin b){
this.ctype=ctype;
this.min_sal=min_sal;
this.year_fee=year_fee;
this.jperks=jperks;
this.rewards=rewards;
this.bankAdmin=b;
}
public BankAdmin getBankAdmin() {
return bankAdmin;
}
public void setBankAdmin(BankAdmin bankAdmin) {
this.bankAdmin = bankAdmin;
}
}
<强> CardDao 强>
@Repository
@Transactional
public class CardsDao{
@PersistenceContext
EntityManager em;
@Autowired
BankAdminDao bad;
public void save(Card cards, int bankId) {
BankAdmin bank = bad.getBankAdmin(bankId);
cards.setBankAdmin(bank);
bank.getCards().add(cards);
em.merge(bank);
}
public List<Card> getAllCards() {
List<Card> cardList = (List<Card>)em.createQuery("SELECT c FROM Cards c");
return cardList;
}
public Card getCard(int cardId){
return em.find(Card.class, cardId);
}
}