表关系参考图





由于新手的限制,从银行jsp页提交后和从卡jsp提交后全部集中在一个图像中




我也是stackoverflow的新手,SPRING。我试图用外键概念创建两个表。我遵循了一些关于stackoverflow的示例以及来自其他resourcefull网站的示例,并设法创建两个具有单向关系的表。但是问题是当我从卡片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;
    }




CardDaoImpl

    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;
    }



}




银行道



    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;
    }


}

最佳答案

好的。我已经发布了解决您问题的方法。

首先,Spring框架很棒。该框架具有很多功能,您应该利用它们。我不确定我是否能够涵盖本文中的所有内容,所以请随时问我。

我创建了一个简单的Spring Boot应用程序。我总共收到6个重要文件,这些文件在下面发布。

请注意,我使用大写字母将您的课程重命名为CamelCase。例如BankAdmin。这被认为是编写Java类的标准方法。另请注意,我将Cards重命名为Card,因此请记住还要在数据库中重命名您的表。还记得将bankadmin表重命名为bank_admin。

您需要查看一些注释。 @Transactional@AutowiredPersistenceContext

如此简单快捷的解释。 @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);

    }
    }


银行管理员

    @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.
    }


银行管理员

    @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;
    }
    }


卡道

    @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);
        }
    }

10-04 22:44