Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Spring中建立一对一关系后,我无法获取映射对象_Java_Spring_Rest_Spring Restcontroller_Spring Rest - Fatal编程技术网

Java 在Spring中建立一对一关系后,我无法获取映射对象

Java 在Spring中建立一对一关系后,我无法获取映射对象,java,spring,rest,spring-restcontroller,spring-rest,Java,Spring,Rest,Spring Restcontroller,Spring Rest,我正在尝试建立一个REST应用程序,它有一对一的关系。Komentari可以有一个用户,用户可以有多个Komentari(注释)。在尝试从Komentari类获取映射用户后,我为用户获取空值。我的用户类: @Entity @Table(name = "users") public class Users { @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) priv

我正在尝试建立一个REST应用程序,它有一对一的关系。Komentari可以有一个用户,用户可以有多个Komentari(注释)。在尝试从Komentari类获取映射用户后,我为用户获取空值。
我的用户类:

@Entity
@Table(name = "users")
public class Users {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id = 0;
    @Column(name = "username")
    private String username;
    @Column(name="email")
    private String email;
    @Column(name="password")
    private String password;
    @Column(name = "enabled")
    private boolean enabled = true;

    @ManyToOne(fetch = FetchType.LAZY, targetEntity = Fakultet.class, cascade=CascadeType.ALL)
    @JoinColumn(name="id_fakulteta", nullable = false)
    private Fakultet faks;

    @ManyToMany
    @JoinTable(
            name = "Room_has_Tag",
            joinColumns = @JoinColumn(name = "Room_idRoom"),
            inverseJoinColumns = @JoinColumn(name = "users_id"))
    Set<Room> rooms;

    @OneToMany(mappedBy = "users")
    private List<Komentari> komentari;

    public Users(){};

    public Users(String username, String email, String password, Fakultet fax) {
        this.username = username;
        this.email = email;
        this.password = password;
        faks = fax;

    }

    public Fakultet getFaks() {
        return faks;
    }

    public void setFaks(Fakultet faks) {
        this.faks = faks;
    }
//other getters and setters

}
数据库代码:

create table IF NOT EXISTS users (
                                     id INT AUTO_INCREMENT PRIMARY KEY,
                                     username varchar(255) not null ,
                                     email varchar(255),
                                     password varchar(255) not null,
                                     id_fakulteta int,
                                     enabled boolean
);
CREATE TABLE IF NOT EXISTS komentari (
                                         id INT NOT NULL AUTO_INCREMENT,
                                         id_teme INT NOT NULL,
                                         id_user INT NOT NULL,
                                         id_parent INT NULL,
                                         Content VARCHAR(280) NOT NULL,
                                         datum_kreiranja DATE NOT NULL,
                                         PRIMARY KEY (id),
                                         CONSTRAINT fk_komentari_teme
                                             FOREIGN KEY (id_teme)
                                                 REFERENCES teme (id_teme),
                                         FOREIGN KEY (id_parent)
                                             REFERENCES komentari(id)
                                             ON DELETE NO ACTION
                                             ON UPDATE NO ACTION,
                                         FOREIGN KEY (id_user)
                                             REFERENCES users(id)
                                             ON DELETE NO ACTION
                                             ON UPDATE NO ACTION
);

我的控制器:
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/dodajKoment")
public ResponseEntity<?> makeKom(@RequestBody Komentari komentar) throws Exception {
    System.out.println(komentar);
    //komentar.getUsers() << IS NULL VALUE
    System.out.println(komentar.getUser_id() + " <<USERS ID");
    Optional<Users> us=use.findById(komentar.getUser_id());
    Optional<Tema> tem=this.temarep.findById(komentar.getTema_id());
    Optional<Komentari> kom=this.komentari.findById(komentar.getKomentar_id());
    komentar.setTeme(tem.get());
    komentar.setUsers(us.get());
    komentari.save(komentar);
    return ResponseEntity.ok("Success!");
}
@交叉原点(原点=”http://localhost:3000")
@后映射(“/dodajKoment”)
公共响应性makeKom(@RequestBody Komentari komentar)引发异常{
系统输出打印LN(科门塔尔);
//komentar.getUsers(){
console.log(response.data)
this.setState(prevState=>({
科尔:{
…prevState.kol,
id:response.data.id,
naziv:response.data.naziv
}
}))
})
.catch(错误=>{
console.log(error.response)
这是我的国家({
错误:{
…错误,
成功:“无法加载类别”,
风格:{
尺寸:13,
marginLeft:14,
颜色:“红色”
}
}
})
});
};
手变(活动){
const target=event.target;
常量值=target.value;
const name=target.name;
设tema={…this.state.tema};
tema[名称]=值;
this.setState({tema});
}
异步handleSubmit(事件){
让今天=日期();
让polj=today.split(“”);
let day=polj[1];
设m=polj[2];
设y=polj[3];
设日期=日+'-'+m+'-'+y;
设id=this.props.location.state.id;
event.preventDefault();
log(this.state.tema.id);
const{tema}=this.state;
const{errors}=this.state;
控制台日志(tema);
轴心柱https://bbtstudyroom.ddns.net:8443/createtema', {
id:this.state.tema.id,
纳斯洛夫:这个州,特马,纳斯洛夫,
datumKreiranja:日期,
idKolegij:this.state.kol.id,
内容:this.state.tema.content
},
{
标题:{
“内容类型”:“应用程序/json”
}
})
。然后(响应=>{
console.log(response.data)
这是我的国家({
错误:{
…错误,
成功,
风格:{
尺寸:13,
marginLeft:14,
颜色:“黑色”
}
}
})
setTimeout(函数(){
let link=“/dashboard/”;
console.log(id);
window.location.href=link.concat(id);
}, 2000);
})
.catch(错误=>{
console.log(error.response)
这是我的国家({
错误:{
…错误,
成功:“未能创建帖子!”,
风格:{
尺寸:13,
marginLeft:14,
颜色:“红色”
}
}
})
});
this.setState({errors:{}});
}
render(){
设{tema}=this.state;
返回(
创建帖子
{this.state.errors.succ&&

{this.state.errors.succ}

} 创建帖子 ); }} 导出默认的CreatePost;
这不提供任何可能发生这种情况的信息。创建@RequestBody时附带的注释在哪里?它是否持久化到dB?如果是这样的话,你确定你已经解决了用户问题吗?@JAsgarov添加的js代码足够了吗?我没有看到你在你的代码中的任何地方添加用户,为什么你认为它会在那里?即使是单个用户,也使用多个用户不是一个好主意
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/dodajKoment")
public ResponseEntity<?> makeKom(@RequestBody Komentari komentar) throws Exception {
    System.out.println(komentar);
    //komentar.getUsers() << IS NULL VALUE
    System.out.println(komentar.getUser_id() + " <<USERS ID");
    Optional<Users> us=use.findById(komentar.getUser_id());
    Optional<Tema> tem=this.temarep.findById(komentar.getTema_id());
    Optional<Komentari> kom=this.komentari.findById(komentar.getKomentar_id());
    komentar.setTeme(tem.get());
    komentar.setUsers(us.get());
    komentari.save(komentar);
    return ResponseEntity.ok("Success!");
}
import React, {Component} from 'react'
import axios from "axios";
import '../../style/login.css'


class CreatePost extends Component{
    constructor(props) {
        super(props);
        this.state = {
            tema:{
                id:'',
                naslov:'',
                datumKreiranja:Date().toLocaleString(),
                content:''
               },
            kol:{
                id:0,
                naziv:''
            },
            errors:{}
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentDidMount() {
        this.getKolegij();
    }


    async getKolegij() {
        let id=this.props.location.state.id;
        const {errors} = this.state;
        axios.post('/kolegijid', id, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                console.log(response.data)
                this.setState(prevState => ({
                  kol: {
                       ...prevState.kol,
                           id: response.data.id,
                           naziv:response.data.naziv

                   }
               }))
            })
            .catch(error => {
                console.log(error.response)
                this.setState({
                    errors:{
                        ...errors,
                        succ: "Couldn't load categories",
                        style:{
                            fontSize: 13,
                            marginLeft: 14,
                            color: 'red'

                        }
                    }
                })
            });
    };


    handleChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;
        let tema = {...this.state.tema};
        tema[name] = value;
        this.setState({tema});
    }

    async handleSubmit(event) {
        let today=Date().toLocaleString();
        let polj=today.split(" ");
        let day=polj[1];
        let m=polj[2];
        let y=polj[3];
        let date=day+'-'+m+'-'+y;
        let id=this.props.location.state.id;
        event.preventDefault();
        console.log(this.state.tema.id);
        const {tema} = this.state;
        const { errors } = this.state;
        console.log(tema);
        axios.post('https://bbtstudyroom.ddns.net:8443/createtema', {
            id: this.state.tema.id,
            naslov: this.state.tema.naslov,
            datumKreiranja:date,
            idKolegij:this.state.kol.id,
            content:this.state.tema.content
        },
            {
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                console.log(response.data)
                this.setState({
                    errors:{
                        ...errors,
                        succ: "Success!",
                        style:{
                            fontSize: 13,
                            marginLeft: 14,
                            color: 'black'

                        }
                    }
                })
                setTimeout(function() {
                    let link="/dashboard/";
                    console.log(id);
                    window.location.href = link.concat(id);
                }, 2000);
            })
            .catch(error => {
                console.log(error.response)
                this.setState({
                    errors:{
                        ...errors,
                        succ: "Failed to create post!",
                        style:{
                            fontSize: 13,
                            marginLeft: 14,
                            color: 'red'

                        }
                    }
                })
            });

        this.setState({errors: {}}) ;
    }







    render() {
        let {tema} = this.state;
        return (
            <div className="container" id="cont">
                    <form onSubmit={this.handleSubmit}>
                        <h1>Create Post</h1>
                        <div className={'inp1'}>
                            <input id={'naslov'} type={"text"} name="naslov" value={tema.naslov} placeholder={"Header"} onChange={this.handleChange} />
                        </div >
                        <textarea id={'textc'} name="content" value={tema.content} placeholder={"Content"} onChange={this.handleChange}  rows="4" cols="50"/>
                        {this.state.errors.succ &&
                        <p style={this.state.errors.style}>{this.state.errors.succ}</p>}
                        <button type={'submit'} className={'btn1'}>Create Post</button>
                    </form>
                </div>


        );
    }}


export default CreatePost;